Jump to content
  • Advertisement
Sign in to follow this  
InsaneBoarder234

[web] PHP/MySQL - Help with SELECT query

This topic is 3994 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Given the following PHP code:
$result = mysql_query("SELECT * FROM `messages` WHERE `topic`=`" . $topic . "` AND `post`=`" . $post . "` LIMIT 0,1");
if(!$result)
{
    die();
}
Will die() be executed if zero rows are returned by the query? I'm writing a function where I want to check if a record does not exist within my database given the two parts of the primary key and I need to be able to differentiate between three cases: internal error (i.e. from mysql_query); 0 rows found; and 1 row found.

Share this post


Link to post
Share on other sites
Advertisement
I believe that a valid resource will be returned even if there are 0 rows. That is, mysql_query should only return false when an error (e.g. syntax, permission) occurs.

Share this post


Link to post
Share on other sites
You could try something like this -
$query = 'blah';
$result = mysql_query( $query )
or die( 'internal error in the query' );

if ( mysql_num_rows( $result ) == 0 ) {
// 0 rows returned
}
else if ( mysql_num_rows( $result ) == 1 ) {
// 1 row returned
}

mysql_free_result( $result );

Alternatively, you could change your SQL around a little to make it a little cleaner -
$query = 'SELECT COUNT(*) as `count` FROM `messages` WHERE blah blah blah';
$result = mysql_query( $querey )
or die( 'internal error in the query' );

// COUNT(*) is guarenteed to return a single row, so you shouldn't
// need to check if the row is valid. I think.

$row = mysql_fetch_array( $result, MYSQL_ASSOC );

if ( $row['count'] == 0 ) {
// 0 rows will be returned
}
else if ( $row['count'] == 1 ) {
// 1 row returned
}

mysql_free_result( $result );

The second one is really only useful if you're not interested in the contents of the rows, since it just fetches the count. On the other hand, if all you want is the count, doing a SELECT * is kind of wasteful.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!