Sign in to follow this  

[web] PHP/MySQL - Help with SELECT query

This topic is 3778 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
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

This topic is 3778 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this