在 PHP 中,要获取查询结果的 num_rows(即查询返回的行数),您需要使用 MySQLi 或 PDO 扩展。以下是两种方法的示例:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询语句
$sql = "SELECT * FROM myTable";
$result = $conn->query($sql);
// 获取查询结果的 num_rows
if ($result->num_rows > 0) {
// 输出每行数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
// 创建连接
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 查询语句
$stmt = $conn->prepare("SELECT * FROM myTable");
$stmt->execute();
// 设置结果集为关联数组
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
// 获取查询结果的 rowCount
$num_rows = $stmt->rowCount();
if ($num_rows > 0) {
// 输出每行数据
foreach($stmt->fetchAll() as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 结果";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
这两个示例都会获取查询结果的 num_rows,并根据结果输出相应的信息。请根据您的实际情况选择合适的方法。