check if table is empty

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
RuffRyder
Forum Newbie
Posts: 11
Joined: Thu Apr 08, 2004 7:00 am
Location: Belgium

check if table is empty

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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)
User avatar
RuffRyder
Forum Newbie
Posts: 11
Joined: Thu Apr 08, 2004 7:00 am
Location: Belgium

Post by RuffRyder »

thx m8,
works fine now

grtz
RuffRyder
Post Reply