How can I check if a table is empty?

Asked

Viewed 2,725 times

3

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

  • You can use the non-count function of sql http://www.w3schools.com/sql/sql_func_count.asp

  • @Reynnan Recomendo ler sobre o site w3schools http://www.w3fools.com/ http://meta.stackoverflow.com/questions/280478/why-not-w3schools-com

2 answers

4

Select and check the total number of lines:

$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'];
    }
}
  • 3

    Bia, if you make one SELECT FIRST(1)NOME_CAMPO FROM tabela gets higher performance.

  • mysql_* functions are obsolete

  • @Júniormoreira FIRST(1)?

  • 1

    Mysql would be 'SELECT field FROM table LIMIT 1'

2

You will need to make 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;

In the first line, where you have DB::prepare(...); DB is the connection class (I particularly use DB, it goes from programmer to programmer).

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.