Page 1 of 1

Error in PHP code

Posted: Tue Feb 14, 2012 8:13 pm
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.

Re: Error in PHP code

Posted: Tue Feb 14, 2012 10:39 pm
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();

Re: Error in PHP code

Posted: Wed Feb 15, 2012 5:33 am
by Celauran
You're missing the closing quote.

Code: Select all

$dbh = connectdb('mydb);

Re: Error in PHP code

Posted: Wed Feb 15, 2012 5:58 am
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