tags:

views:

47

answers:

4

How to list records for a query and to display 'no records' when no rows returned using a single query?

Now i'm using a count(*) query or using the mysql_num_rows and then another query in different result set to list data..

Please tell me whether its possible with a single query..?

A: 

why do you need another query after mysql_num_rows?
why not to just run your query and then check results with mysql_num_rows?

Col. Shrapnel
A: 

Try Something like following

   if (mysql_num_rows ==  '0')
       'No Records'
    else
       //YOUE CODE HERE
Salil
+2  A: 

Important: I assume that the OP uses PHP as (s)he mentions mysql_num_rows. And I hope (s)he will tell me if I am wrong.


It is your job in PHP to check whether the result is an empty set or not. I don't understand why you have to do another query. Maybe you have to clarify your question.

Here a more complete example:

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);

// If if result set contains rows
if(0 == mysql_num_rows($result)) {
    echo 'no records';
}
else { // Loop over the result set
    while(row = mysql_fetch_array($result)) {
       // do whatever you want with the data here
    }
}

Reference: mysql_num_rows, mysql_fetch_array


Even if you don't use PHP, the approach is the same in other languages and there should be similar functions available.

Felix Kling
A: 

Its fairly straight forward. mysql_fetch_assoc returns false when there are no more records to fetch. You can use this fact to create a loop such as this:

$query  = sprintf( "SELECT * FROM mytable" );
$result = mysql_query( $query, $link ) or die( mysql_error( $link ) );
$record = mysql_fetch_assoc( $token );

// $record will be false if not a single record was found

if ( $record === false ) {
    // Display no matching records found
}

// PHP will enter and re-enter the following loop if $record is not false

while ( $record ) {
    // Display record details
    // and fetch next record
    $record = mysql_fetch_assoc( $token );
}
Salman A