简体   繁体   中英

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. However, if I try echoing $london or $york I get a fatal error. 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 .

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:

$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 :

$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:

$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

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