Function to check if the table is empty?

This function always returns 1 (TRUE), is there a better way to find out if the table is empty?

function isEmpty($tableName)
{
    $sql = "SELECT * FROM $tableName";
    $q = mysql_query($sql);
    if (mysql_num_rows==0)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
echo isEmpty("mytable");

Answer 1, authority 100%

You have an error in the line if (mysql_num_rows==0) ​​should be if (mysql_num_rows($q)==0)


Answer 2, authority 67%

function isEmpty($table){
 $db=new PDO('$dsn', '$user', '$password');
 $req=$db->prepare("select table_rows from information_schema.tables where table_name=?");
 $req->execute(array($table));
 return $req->fetchColumn()?false:true;
}

Answer 3

Use the SQL EXISTS predicate, its only parameter is subquery, if the subquery returns any result set EXISTS returns TRUE.

Leave a reply

Please enter your comment!
Please enter your name here