如何将 MySQL 代码转换为 PDO 语句?
为了将最初的 if 语句更改为 PDO 语句,您需要首先使用 PDO 建立连接。具体方法如下:
// Define database connection parameters $db_host = "127.0.0.1"; $db_name = "name_of_database"; $db_user = "user_name"; $db_pass = "user_password"; try { // Create a connection to the MySQL database using PDO $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); } catch (PDOException $e) { echo 'Failed to connect to the database: ' . $e->getMessage(); }
接下来,您需要修改现有代码以将准备好的语句与 PDO 结合使用。这是代码的更新版本:
// Initialize variables $id = $_SESSION['u_id'] ?? NULL; $email = NULL; if($id) { // Prepare the SQL statement $sql = "SELECT email FROM users WHERE u_id = :id"; $query = $pdo->prepare($sql); // Bind the parameter and execute the query $query->bindParam(':id', $id, PDO::PARAM_STR); $query->execute(); // Fetch the result $row = $query->fetch(PDO::FETCH_OBJ); $email = $row->email; } // Initialize other variables $optionOne = $_POST['optionOne'] ?? ""; $optionTwo = $_POST['optionTwo'] ?? ""; $newSuggestion = $_POST['new-suggestion'] ?? ""; // Check if the form was submitted if($newSuggestion and $id and $email and $optionOne and $optionTwo) { // Prepare the SQL statement $sql = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (:id, :email, :option_1, :option_2)"; $query = $pdo->prepare($sql); // Bind the parameters and execute the query $query->bindParam(':id', $id, PDO::PARAM_STR); $query->bindParam(':email', $email, PDO::PARAM_STR); $query->bindParam(':option_1', $optionOne, PDO::PARAM_STR); $query->bindParam(':option_2', $optionTwo, PDO::PARAM_STR); $query->execute(); } else { echo "All options must be entered."; }
此更新的代码使用带有 PDO 的准备好的语句来提高安全性和效率。它还使用 NULL 合并运算符 (??) 在变量为 null 时为其分配默认值。
以上是如何将 MySQL 代码转换为 PDO 语句以提高安全性和效率?的详细内容。更多信息请关注PHP中文网其他相关文章!