我有此代码:
$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;
如果我回显$total
,则会产生5
,这很好。但是,如果我尝试回显$london
或$york
,则会出现致命错误。这是为什么?这两个变量都应产生查询产生的行数。是吗?
谢谢。
答案 0 :(得分:0)
您的echo
返回错误,因为->query()
的结果不是 布尔值,而是 mysqli_result
。< / p>
是的,您可以将这些结果加在一起,但是您绝对应该避免这样做(因为这样会产生意外的结果)。
您可能想要利用 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
但是请注意,我会强烈建议使用 prepared statements 来防止 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
您甚至可以通过在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