简体   繁体   中英

check if MySQL table is empty

I want to check if my table is empty I've tried this "which I think that is the solution"

$test_empty="SELECT *FROM objectif where 1 ";
if(empty($test_empty))
{
     echo "I m here";
}

But it seems that it doesn't work.

Depending on how you are connecting to your database (for example, using mysqli):

$db = new mysqli("localhost","username","password","dbname");

$check = $db->query("SELECT COUNT(*) FROM objectif");

if ($check->num_rows == 0 || $check->fetch_field() == 0){
   echo "table is empty";
}else{
    echo "table is not empty";
}

Currently, your code isn't actually connecting to the database or querying the table - you are essentially just checking if the variable $query is empty (which it never will be, as it contains a string!

Running a query to fetch the number of records and checking that as per the code above is one way to do this.

Use this

$mysqli = new mysqli("localhost","root","","db");

if ($result = $mysqli->query("SELECT * FROM `table` LIMIT 1"))
{

    if ($obj = $result->fetch_object())
    {

        echo "NOT EMPTY";

    }
    else
    {

        echo "empty";

    }


    $result->close();

}
$mysqli->close();

Please try below code :

$test_empty="SELECT * FROM objectif";
$query = mysql_query($test_empty);
if(mysql_affected_rows() > 0)
{
     echo "It is Empty";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM