简体   繁体   English

检查 MySQL 表是否为空

[英]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):取决于您连接到数据库的方式(例如,使用 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!目前,您的代码实际上并没有连接到数据库或查询表 - 您实际上只是在检查变量 $query 是否为空(它永远不会是空的,因为它包含一个字符串!

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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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