使用 MySQLi 在 PHP 中最佳化預備語句的使用
您的程式碼似乎缺少參數與預先準備語句的綁定。根據 mysqli::prepare 文檔,在執行語句之前必須綁定參數標記。
// Bind parameters for the first insertion $name1 = 'one'; $age1 = 1; $stmt->bind_param('si', $name1, $age1); // Execute for the first insertion $stmt->execute(); // Bind parameters for the second insertion $name2 = 'two'; $age2 = 1; $stmt->bind_param('si', $name2, $age2); // Execute for the second insertion $stmt->execute();
mysqli 的優點
雖然mysqli 不是唯一的函式庫支援準備好的語句,它提供了幾個優點:
錯誤處理的完整範例
這裡是在中使用準備好的語句的完整範例PHP 與MySQLi,包括錯誤處理:
// Database connection $mysqli = new mysqli("localhost", "root", "root", "test"); if ($mysqli->connect_errno) { echo "Failed to connect: " . $mysqli->connect_error; exit; } // Prepare statement $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)"); if (!$stmt) { echo "Prepare failed: " . $mysqli->error; exit; } // Bind parameters for the first insertion $name1 = 'one'; $age1 = 1; $stmt->bind_param('si', $name1, $age1); // Execute for the first insertion $stmt->execute(); if ($stmt->errno) { echo "Execution failed: " . $stmt->error; exit; } // Bind parameters for the second insertion $name2 = 'two'; $age2 = 1; $stmt->bind_param('si', $name2, $age2); // Execute for the second insertion $stmt->execute(); if ($stmt->errno) { echo "Execution failed: " . $stmt->error; exit; } // Selection statement $stmt = $mysqli->prepare("SELECT * FROM users WHERE age = ?"); if (!$stmt) { echo "Prepare failed: " . $mysqli->error; exit; } // Bind parameters for selection $age = 1; $stmt->bind_param('i', $age); // Execute selection $stmt->execute(); if ($stmt->errno) { echo "Execution failed: " . $stmt->error; exit; } // Fetch results $result = $stmt->get_result(); if (!$result) { echo "Fetch failed: " . $stmt->error; exit; } while ($row = $result->fetch_assoc()) { echo $row['name'] . " " . $row['age'] . "<br>"; }
以上是如何使用 MySQLi 最佳化 PHP 中預先準備語句的使用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!