在PHP中,fetch_array()
函数用于从结果集中获取一行作为数组
while
循环:$result = mysqli_query($connection, $sql);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
// 处理每一行数据
echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}
} else {
echo "查询失败";
}
foreach
循环:$result = mysqli_query($connection, $sql);
if ($result) {
foreach (mysqli_fetch_all($result, MYSQLI_ASSOC) as $row) {
// 处理每一行数据
echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}
} else {
echo "查询失败";
}
注意事项:
mysqli_prepare
)以提高安全性并防止SQL注入。mysqli_free_result()
释放结果集内存。