Jump to content

PHP Exposes MySQL Error, MySQL Exposes No Error


mickeeyone

Recommended Posts

I have code retrieving a max id column in mysql and the code performs and works correctly, however I receive this error:

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in ...

 

Here is the code:

$query = "SELECT MAX(`pageId`) AS `pageId` FROM `pages` WHERE 1";
	$result = mysql_query($query);
	while($row = mysql_fetch_assoc($result)) 
	{
		$pageId = $row['pageId'] + 1; 
		$query = "INSERT INTO `pages` VALUES('', '$pageId', '$pageName', '$pageTitle', '$pageBody', now(), now(), '$pageAuthor', '$authorIPCreated', '$authorIPCreated')";
		$result = mysql_query($query) or die('Error: ' . mysql_error());
	}

$query = "SELECT MAX(`pageId`) AS `pageId` FROM `pages` WHERE 1";

 

If you don't have a condition to apply to a query, then just omit the WHERE clause entirely.

$query = "SELECT MAX(`pageId`) AS `pageId` FROM `pages`";

 

Change your first mysql_query line to also include an or die with the mysql error message so you can see what mysql is complaining about:

$query = "SELECT MAX(`pageId`) AS `pageId` FROM `pages`";
$result = mysql_query($query) or die('Error: ' . mysql_error());
while($row = mysql_fetch_assoc($result)) 

 

Also selecting the max page id and doing +1 and using for a new id is a poor method, you should use mysql's AUTO_INCREMENT feature instead to let mysql automatically generate the IDs.  That way you do not have to worry about possible duplicates from simultaneous requests or re-used IDs from a delete.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.