Page 1 of 1

check if table is empty

Posted: Fri Apr 09, 2004 6:55 am
by RuffRyder
hi all,

got a little question again; how can i check a mysql table if it's empty, so it doesn't contain any records.
i was thinking somewhere along the lines of:
if(mysql_query("select * from table",$conn)=" "){
//...
}

but i don't think that's quite right, is it? :)
grtz
RuffRyder

Posted: Fri Apr 09, 2004 7:02 am
by markl999
$res = mysql_query("select * from table") or die(mysql_error());
if(mysql_num_rows($res) == 0){
//no rows returned, which means an empty table in the above query
} else {
//some rows were returned
}

But selecting * just to count the rows isn't a great idea, might want to do this instead:
$res = mysql_query("SELECT COUNT(id) AS total FROM table") or die(mysql_error());
$row = mysql_fetch_assoc($res);
if($row['total'] == 0){
//no rows returned
} else {
//some rows returned
}

(where id is some column in your table)

Posted: Fri Apr 09, 2004 7:07 am
by RuffRyder
thx m8,
works fine now

grtz
RuffRyder