Hello All,
I was wondering if there is a MySQL command to check if a particular table is emtpy. I have the following code snippet here:
if (TABLE_IS_EMTPY) {
echo "DO_SOMETHING_HERE";
} else {
for ($k=0; $row = mysql_fetch_row($model_result); $k++) {
echo "DO_SOMETHING_ELSE";
}
}
I’ve searched through the MySQL documentation, but didn’t find anything.
Any ideas?
Thanks
i don’t know whether you want to check if the table is empty, or if a certain query returned no rows.
to check if the whole table has any rows:
<?php
$rows = mysql_result(mysql_query('SELECT COUNT(*) FROM table'), 0);
if (!$rows) { /* Table is empty */ }
?>
to check if a certain query (with a WHERE etc.) returned no rows:
<?php
if (!mysql_num_rows($result))
{
// No rows
}
else
{
// Fetch the rows
}
?>
DOETH.
Total brain lapse. Didn’t realize you could check the num_rows just from the query handle
Duh.
Thanks for the reminder!!
I appreciate it.
Please note that “SELECT COUNT(*) FROM table” will ALWAYS return one record. If the table is empty, it will return 0.
So…
<?
$rows = mysql_result(mysql_query('SELECT COUNT(*) FROM table'), 0);
?>
$rows will NEVER EVER be indefined.
I just used the following, worked great:
$model_query = "SELECT model FROM ".$table_array[$j]." ORDER BY model";
$model_result = mysql_query($model_query,$db);
if (!mysql_num_rows($model_result)) {
// Do Something Here
} else {
// Do Something Else
}
Mincer
March 19, 2003, 1:21pm
6
Please note that “SELECT COUNT(*) FROM table” will ALWAYS return one record. If the table is empty, it will return 0.
So…
<?
$rows = mysql_result(mysql_query('SELECT COUNT(*) FROM table'), 0);
?>
$rows will NEVER EVER be indefined.
However, ( ! $rows ) evaluates to false if $rows is 0 anyway.
Matt.