How can I check if a table is empty?

3

I want to check if a MySQL table is empty (no record) with PHP, how can I do that? What kind of consultation do I make to make sure of this?

    
asked by anonymous 20.10.2016 / 05:42

2 answers

4

Make a select and check the total number of rows:

$select = mysql_query("SELECT id FROM tabela LIMIT 1");

if(empty(mysql_num_rows($select))) 
{
    echo "Tabela está vazia";
} 
else 
{          
    while($dados=mysql_fetch_array($select)) 
    {
       echo $dados['coluna'];
    }
}
    
20.10.2016 / 11:07
2

You will need to do a select and check the return.

This example is in PDO.

$sql = DB::prepare(" SELECT COUNT(1) FROM table ");
$sql->execute();

$count = ( $sql->rowCount() < 1 ? "Vazio" : "Eita, tem alguma coisa aqui.");

echo $count;

On the first line, where DB :: prepare (...); the DB is the connection class (I particularly use DB, this goes from programmer to programmer).

Visit the W3C website as your friend indicated and take a look at some tutorials on the internet, you will find several.

    
20.10.2016 / 19:35