This function returns always 1 (TRUE), maybe there are better options 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"); 
  • What is mysql_num_rows? Was it a function like before? - alexlz 2:07 pm
  • Yes, thanks, it is quite logical, but does echo FALSE print as zero or nothing at all? - Smash
  • False will be like zero, if you need anything then use null. - evgeniy
  • Well, I do not know my echo FALSE displays nothing at all, emptiness, not 0 and not null. - Smash
  • although if so: if (FALSE == null) {echo "TRUE";} else echo "FALSE"; or if (FALSE == 0) {echo "TRUE";} else echo "FALSE"; then everything is correct, okay, thanks, this is how I have already moved away from the topic. - Smash

3 answers 3

 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; } 

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

      Use the SQL EXISTS predicate, it has a single subquery parameter if the subquery returns any result set EXISTS returns TRUE.

      • Is it possible to use this predicate in MySQLi? I would like to see an example, but for now I'll walk along the docks. - Smash