Error in PHP code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
elpg101
Forum Newbie
Posts: 1
Joined: Tue Feb 14, 2012 8:07 pm

Error in PHP code

Post by elpg101 »

Hi,

I have the following code, connectdb() is my function which connects to a db,

Code: Select all


		$dbh = connectdb('mydb);
		$sql = "SELECT title,description,img FROM news ORDER BY id DESC LIMIT 4";
		$stmt = $dbh->prepare($sql);
		$stmt->execute();
		$result = $stmt->fetchAll();

			foreach ($result as $row)
				{
					$news[]			= $row['title'];
					$img[] 			= $row['img'];
					$description[]	= $row['description'];
				}

		$dbh = null;
and this is outputting the error,
Fatal error: [] operator not supported for strings in /home/sifelou1/public_html/index2.php on line 31

line 31 is $description[] = $row['description'];, when I remove this the code works perfectly. It is stored as a varchar in the database and so are the news and image columns. I really can't understand why it isn't working, any help would be appreciated! Thanks in advance.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Error in PHP code

Post by twinedev »

My best guess would be that $description was already used somewhere else in the script and assigned a string, where as $news and $img were never used so the first time you assigned to it, PHP figured out they need to be an array, or they were already defined as an array.

This is why it is best practice to define arrays before using them. If you are only meaning to use $news $img $description to hold items from the loop, then add the following before the foreach() statement:

Code: Select all

$news = array();
$img = array();
$description = array();
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Error in PHP code

Post by Celauran »

You're missing the closing quote.

Code: Select all

$dbh = connectdb('mydb);
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Error in PHP code

Post by twinedev »

Wow, I completely missed that, and the fact that everything after that up to $row['title'] was the same color. I think I need sleep, Good catch!

-Greg
Post Reply