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.).