对于多个查询,您需要在调用另一个查询之前使用多查询或关闭结果。例如,如果您以面向对象的风格编写。
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM mytable";
$result=$conn->query($sql);
echo $result->num_rows;
$sql="SELECT id FROM mytable";
$result2=$conn->query($sql);
echo $result2->num_rows; // does not work because result was not closed.
为了让它工作,写这个。
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM mytable";
$result=$conn->query($sql);
echo $result->num_rows;
$result->close(); //*********notice this new line. result
//needs to be closed before calling another query
$sql="SELECT id FROM mytable";
$result2=$conn->query($sql);
echo $result2->num_rows; // **this does work because previous result
// was closed.
如果您需要一次执行多个查询,或者需要在完成前一个行的输出之前执行一个查询,请使用多查询。我使用多查询是因为第二个原因,在输出前一个的所有行之前获取另一个查询。这对于嵌套查询很重要,例如一个在另一个中间的查询,例如在论坛中的多个嵌套线程中,或者对于某些网页上使用的嵌套回复。
这是在另一个查询中间完成的一个查询的示例。
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM mytable";
$conn->multi_query($sql);
$result=$conn->store_result();
$count=0;
while($row = $result->fetch_assoc()) {
echo "$result['id'] $result['name'];
if ($count==0) {
// now you can do another query in the middle of this one
$sql="SELECT id FROM mytable";
$conn->multi_query($sql);
$result2=$conn->store_result();
$row2=$result2->fetch_assoc();
echo "result of second query is: $row2['id'] $row2['name']";
}
$count=$count+1;
}