使用 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中文网其他相关文章!