tags:

views:

97

answers:

2

Question title says it all. I'm using PHP5 and MySQL.

EDIT:

I'm using mysql_...() functions.

+7  A: 
if (mysql_num_rows($query_identifier) == 0)
  echo "Query returned 0 rows";

Additionally, mysql_query() returns false in case of an error.

Manual: MySQL functions in PHP

Pekka
mysql_query() isn't returning false for some reason, but I'm limiting the query with a WHERE clause on a test query and I'm sure that the data won't match the query.
Moshe
@Moshe, mysql_query only returns false when there is an _error_. If your WHERE clause is not matching any rows then you will, unsurprisingly, have no results.. not an error though.
Jonathan Fingland
@Jonaythan - So I need to use num_rows, then, right?
Moshe
@Moshe: If you want to count results, then yes. I just mentioned the `false` case because it is important to provide for that as well.
Pekka
It depends on your code. `mysql_num_rows()` returns the number of result rows - if it returns 0, then the result is empty. BUT you may also just want to read the result and do nothing if no result row arrives, e.g. `while( $row=mysql_fetch_array($rs,MYSQL_ASSOC) ) { do_something_with_row($row); }`. What more do you need or want?
frunsi
I mean, in most cases you do not need to call `mysql_num_rows()`, because when you READ the result, you will know that the result is empty!
frunsi
Depends what you want to do. If you want to do a "this table is empty." output, you may need to count them.
Pekka
@Moshe: Yes. As Pekka and frunsi have pointed out, `mysql_num_rows()` will tell you how many rows are in your result. If it returns 0, then your result set is empty. frunsi's approach above is also correct, though, mysql_num_rows can be useful in other cases as well, e.g. displaying the number of results in addition to the results themselves without keeping a running count of the results.
Jonathan Fingland
Thanks. Worked like a charm. (If you believe in that sort of thing.) My psuedocode: *if(mysql_num_rows($query) > 0){//do something}else{echo 'nothing doing';}*
Moshe
A: 

If you are using mysqli_ functions, you can call $stmt->num_rows(). But only after calling $stmt->store_result() to ensure all the rows have been returned.

Kibbee
@Kibbee: you might as well delete this. the OP pointed out that he is using the mysql_ functions in an edit 6~7 minutes prior to your answer.
Jonathan Fingland