mysql_query mysqli_query_如何在PHP中使用mysqli_query()?
小編典典
我必須承認,mysqli_query()手動輸入沒有包含有關如何獲取多行的干凈示例。可能是因為例程是如此的例程,數十年來一直被PHP人士所熟知:
$result = $link->query("DESCRIBE students");
while ($row = $result->fetch_assoc())
{
// to print all columns automatically:
foreach($row as $value) echo "
$value";// OR to print each column separately:
echo "
"$row['Field'],"",$row['Type'],"\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 them
foreach ($header as $value) echo "
$value";// finally printing the data
foreach ($data as $row)
{
foreach($row as $value) echo "
$value";}
某些主機可能不支持該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();
2020-05-17
總結
以上是生活随笔為你收集整理的mysql_query mysqli_query_如何在PHP中使用mysqli_query()?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信息学奥赛一本通 1958:【12NOI
- 下一篇: 信息学奥赛一本通 1324:【例6.6】