【发布时间】:2014-12-17 21:56:48
【问题描述】:
我需要查询 db 以获取信息,在 foreach 中我还需要进行更多查询来选择和计算行数(只是检查)。如果我需要计算行数,我想我无法加入查询...
所以我有这个:
// first query here
$Items = $mysqli->query("SELECT * ...");
foreach ($Items as $i => $ItemInfo) {
// some checks here before start printing db data
$a = $mysqli->query("SELECT * ...");
$num_a = mysqli_num_rows($a); // 61
$b = $mysqli->query("SELECT * ...");
$num_b = mysqli_num_rows($b); // 63
}
我明白了:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\views\site\reto.php on line 61
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\views\site\reto.php on line 63
我尝试了一些来自 php.net 手册中 cmets 的示例,但不起作用:
<?php
// WORKING CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
while ($mysqli->next_result()) // flush multi_queries
{
if (!$mysqli->more_results()) break;
}
$mysqli->query(" SQL statement #1 ; ") // now executed!
$mysqli->query(" SQL statement #2 ; ") // now executed!
$mysqli->query(" SQL statement #3 ; ") // now executed!
$mysqli->query(" SQL statement #4 ; ") // now executed!
?>
也许我做错了:
// multi_query here
$Items = $mysqli->multi_query("SELECT * ..."); // doing a normal query???
while ($mysqli->next_result()) // flush multi_queries {
if (!$mysqli->more_results()) break;
}
foreach ($Items as $i => $ItemInfo) {
// some checks here before start printing db data
$a = $mysqli->query("SELECT * ...");
$num_a = mysqli_num_rows($a);
$b = $mysqli->query("SELECT * ...");
$num_b = mysqli_num_rows($b);
}
我得到了这个:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\views\site\reto.php on line 50
也许我不需要 multi_query 因为我不需要任何额外的查询...
无论如何,我不在乎使用准备好的语句,我可能会在一切正常时使用它们。但问题是我需要第一个查询(在 foreach 之外),但我无法关闭它,因为我在 foreach 中打印数据,而且我还需要在 foreach 中进行这些检查(行数)。
提前致谢!
编辑:添加查询:
if (login_check($mysqli) == true) {
$id = $_SESSION['user_id'];
}
else {
$id = get_ip_address();
}
$status_id = 1; // status message id
if ($stmt = $mysqli->prepare(" (SELECT * FROM user_uploads ORDER by up_time DESC)
UNION
(SELECT COUNT(*) rowCount FROM likes WHERE user_id = ? AND status_id = ? AND img_id = ?)
UNION
(SELECT COUNT(*) rowCount2 FROM likes WHERE status_id = ?)")) {
$stmt->bind_param('iii', $id, $status_id, $status_id, $img_id);
$Items = $stmt->execute(); // get photos
}
foreach ($Items as $ItemInfo) {
//how to get the rowCount???
}
【问题讨论】:
-
你必须使用
mysqli_fetch_assoc... -
嵌套查询效率极低,你的代码会越来越慢;尝试使用 JOIN,这样您就可以一次执行单个查询来检索所有数据,而不是 10、100、1000 个单独的查询
-
好的,但是如何计算 JOIN 查询中的行数?
-
显示您的实际查询,我们也许可以回答如何将它们组合成一个查询
-
谢谢,我刚刚编辑了。