我必须承认,
mysqli_query()手动输入没有包含有关如何获取多行的干净示例。可能是因为例程是如此的例程,数十年来一直被PHP人士所熟知:
$result = $link->query("DESCRIBE students");while ($row = $result->fetch_assoc()){ // to print all columns automatically: foreach($row as $value) echo "<td>$value</td>"; // OR to print each column separately: echo "<td>"$row['Field'],"</td><td>",$row['Type'],"</td>n";}如果要打印列标题,则必须先将数据选择到嵌套数组中,然后使用第一行的键:
// getting all the rows from the query// note that handy feature of OOP syntax$data = $link->query("DESC students")->fetch_all(MYSQLI_ASSOC);// getting keys from the first row$header = array_keys(reset($data));// printing themforeach ($header as $value) echo "<td>$value</td>";// finally printing the dataforeach ($data as $row){ foreach($row as $value) echo "<td>$value</td>";}某些主机可能不支持该
fetch_all()功能。在这种情况下,请
$data按通常方式填充数组:
$data = [];$result = $link->query("DESC students");while ($row = $result->fetch_assoc()){ $data[] = $row;}我必须添加两个重要说明。
您必须将mysqli配置为自动引发错误,而不是手动检查每个mysqli语句的错误。为此,请在此行 之前 添加
mysqli_connect()
:mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
最重要的说明: 与相比
mysql_query()
,mysqli_query()
用途非常有限。仅 当在查询中不使用任何变量时, 才可以使用此函数 。 如果要使用任何PHP变量,则不应使用mysqli_query()
,而应始终遵循 准备好的语句 ,例如:$stmt = $mysqli->prepare("SELECt * FROM students WHERe class=?");$stmt->bind_param(‘i’, $class);
$stmt->execute();
$data = $stmt->get_result()->fetch_all();
我不得不承认,这有点罗word。为了减少代码量,您可以使用PDO或采用简单的辅助函数来执行内部的所有准备/绑定/执行业务:
$sql = "SELECt * FROM students WHERe class=?"; $data = prepared_select($mysqli, $sql, [$class])->fetch_all();



