简体   繁体   English

如何使用MySQL查询获取行数

[英]How to use MySQL query to get the number of rows

I have this code:我有这个代码:

$london = $mysqli->query("SELECT room FROM rooms WHERE location='london' AND status='1'");
$york = $mysqli->query("SELECT room FROM rooms WHERE location='york' AND status='1'");
$total = $london + $york;

If I echo $total it produces 5 which is fine.如果我 echo $total它会产生5这很好。 However, if I try echoing $london or $york I get a fatal error.但是,如果我尝试回显$london$york ,则会出现致命错误。 Why is that?这是为什么? Both variables should produce the number of rows resulting from the query.这两个变量都应该产生查询产生的行数。 Isn't it?不是吗?

Your echo returns an error because the result of ->query() is not a boolean, but rather a mysqli_result .您的echo返回错误,因为->query()的结果不是布尔值,而是mysqli_result

Yes, you can add these results together, but you should definitely avoid doing so (as it will yeild unexpected results).是的,您可以将这些结果加在一起,但您绝对应该避免这样做(因为它会产生意想不到的结果)。

What you probably want is to make use of fetch_row() to grab the result of the query:您可能想要的是利用fetch_row()来获取查询结果

$result = $mysqli->query("SELECT room FROM rooms WHERE location='london' AND status='1'");
$london = $result->fetch_row();
echo $london[0]; // 2

$result = $mysqli->query("SELECT room FROM rooms WHERE location='york' AND status='1'");
$york = $result->fetch_row();
echo $york[0]; // 3

echo $london + $york; // 5

Note, however, that I would strongly recommend using prepared statements instead to prevent SQL injection :但是请注意,我强烈建议使用准备好的语句来防止SQL 注入

$country = "london";

$stmt = $mysqli->prepare("SELECT room FROM rooms WHERE location=? AND status=?");
$stmt->bind_param("si", $country, 1); 
$stmt->execute(); 
$stmt->bind_result($name, $london_rooms);

echo $london_rooms; // 2

And you can even combine your two queries by using a comma-separated string alongside IN() to prevent having to call your database twice:您甚至可以通过在IN()旁边使用逗号分隔的字符串来组合您的两个查询,以防止必须两次调用您的数据库:

$countries = ['london', 'york'];
$countriesString = implode($countries, ",");

$stmt = $mysqli->prepare("SELECT room FROM rooms WHERE location IN(?) AND status=?");
$stmt->bind_param("si", $countriesString, 1); 
$stmt->execute(); 
$stmt->bind_result($name, $rooms);

echo $rooms; // 5

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

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