Home php Checking "Is the table empty?" PDO

Checking “Is the table empty?” PDO




Faced a problem. How to check “Is the table empty”? Via PDO

Answer 1, authority 100%

$ sql = 'SELECT id FROM table LIMIT 1';
$ result = $ pdo- & gt; query ($ sql);
if (! $ result- & gt; fetch ()) {
  // Empty table
// Or like this
if ($ result- & gt; rowCount () == 0) {
 // Empty table

Answer 2

Make select id from table limit 1 , if it returns an empty result, then the table is empty

Answer 3

The notion “table is empty” is equivalent to the notion “the number of records in the table is equal to zero”. Therefore, we execute the request

SELECT COUNT (*) AS recordscount
FROM tablename

and compare the resulting value of the single recordscount field of the only record in the returned set with zero.

Do not forget to check if an error occurred during the execution of the request (the table may be deleted, damaged, blocked, the connection to the server may “fall apart”, etc.).

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions