How can PHP determine if a query has results?

In PHP, you can use the mysqli_num_rows function to determine if a query has any results. This function returns the number of rows in the query result set.

Here is an example code:

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 执行查询语句
$sql = "SELECT * FROM 表名";
$result = $conn->query($sql);

// 判断查询结果
if ($result->num_rows > 0) {
    // 查询有结果
    // 迭代输出每一行数据
    while($row = $result->fetch_assoc()) {
        echo "字段1: " . $row["字段1"]. " - 字段2: " . $row["字段2"]. "<br>";
    }
} else {
    // 查询无结果
    echo "查询无结果";
}

// 关闭数据库连接
$conn->close();

In the above code, $result->num_rows is used to determine the number of rows in the query result set. If it is greater than 0, it means the query has results; otherwise, it means the query has no results.

bannerAds