」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何透過 PHP 有效地使用 MySQL 中的預先準備語句?

如何透過 PHP 有效地使用 MySQL 中的預先準備語句?

發佈於2024-12-21
瀏覽:186

How to Effectively Use Prepared Statements in MySQL with PHP?

MySQL 中的準備語句入門

準備語句是編寫安全且有效率的 SQL 查詢的重要工具。在本文中,我們將探討如何在 PHP 中的 MySQLi 擴充 mysqli 中使用預先準備語句。

語法錯誤:非物件執行

您遇到的錯誤、「致命錯誤:在非物件上呼叫成員函數execute()」通常表示$stmt 變量未正確初始化或是一個物件。修正方法如下:

$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");

確保您有繼續之前與資料庫的有效連接。

綁定參數

準備好的語句使用參數標記(例如?)來表示輸入值。在執行語句之前,需要將這些值綁定到 PHP 變數。這是一個例子:

$name = 'one';
$age = 1;
$stmt->bind_param('si', $name, $age);

在此範例中,我們將name 參數綁定為字串('s'),將age 參數綁定為整數('i ').

執行語句

參數綁定後,即可執行準備好的語句語句:

$stmt->execute();

處理錯誤

準備好的語句比直接SQL 查詢提供更好的錯誤處理。使用 mysqli_stmt::error 方法擷取錯誤訊息:

if ($stmt->error) {
    die("Error: " . $stmt->error);
}

完整範例

以下是插入、選擇和處理錯誤的完整範例:

// Establish connection
$mysqli = new mysqli("localhost", "root", "root", "test");

// Prepare and bind parameters
$stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");
$stmt->bind_param('si', $name, $age);

// Insert multiple rows
$name = 'one';
$age = 1;
$stmt->execute();
$name = 'two';
$age = 2;
$stmt->execute();

// Prepare and execute select statement
$stmt = $mysqli->prepare("SELECT * FROM users");
$stmt->execute();

// Bind result
$result = $stmt->get_result();

// Process results
while ($row = $result->fetch_assoc()) {
    echo $row['name'] . ", " . $row['age'] . "
\n"; } // Handle errors if ($stmt->error) { die("Error: " . $stmt->error); }

透過使用準備好的語句,您可以防止 SQL 注入攻擊並編寫更健壯、更有效率的 SQL 查詢。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3