mysql_fetch_assoc() problem!!

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
Shazer2
Forum Newbie
Posts: 1
Joined: Sat Sep 25, 2010 3:52 pm

mysql_fetch_assoc() problem!!

Post by Shazer2 »

Code: Select all

<?php
include 'blogpost.php';

// Change this info so that it works with your system.
$connection = mysql_connect('localhost', 'root', '') or die ("<p class='error'>Sorry, we were unable to connect to the database server.</p>");
$database = "datab";
mysql_select_db($database, $connection) or die ("<p class='error'>Sorry, we were unable to connect to the database.</p>");

function GetBlogPosts($inId=null, $inTagId =null)
{
	if (!empty($inId))
	{
		$query = mysql_query("SELECT * FROM blog_posts WHERE id = " . $inId . " ORDER BY id DESC"); 
	}
	else if (!empty($inTagId))
	{
		$query = mysql_query("SELECT blog_posts.* FROM blog_post_tags LEFT JOIN (blog_posts) ON (blog_post_tags.postID = blog_posts.id) WHERE blog_post_tags.tagID =" . $tagID . " ORDER BY blog_posts.id DESC");
	}
	else
	{
		$query = mysql_query("SELECT * FROM blog_posts ORDER BY id DESC");
	}
	
	$postArray = array();
	while ($row = mysql_fetch_assoc($query))
	{
		$myPost = new BlogPost($row["id"], $row['title'], $row['post'], $row['postfull'], $row["author_id"], $row['dateposted']);
		array_push($postArray, $myPost);
	}
	return $postArray;
}
?>
That is my code, when I try and use my blog, it returns this error.

"Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\blog\includes\includes.php on line 24"

I don't know what to do, and I don't know how to solve it, please help!
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: mysql_fetch_assoc() problem!!

Post by califdon »

That error message is telling you that instead of a query resource (a set of records returned by the query), your code is producing a boolean value (undoubtedly a False), so it can't fetch anything. Why would that be? Probably because either your connection failed (not in this case, or you would have gotten the "die" message earlier) or because the query failed. In your code, there is no "die" alternative if the queries fail. You need to add "die" alternatives to the query lines:

Code: Select all

$query = mysql_query("SELECT * FROM blog_posts ORDER BY id DESC") OR die(mysql_error());
If your query fails, you will see the MySQL error message specifying what failed.
Post Reply