这是一个关于如何使用准备好的语句更新 MySQL 数据库中的行的小教程。在这个例子中,我将使用 PHP 的 PDO 对象。
例如,假设我们有一个名为 cars 的表,并且我们想要更新 ID 为“90”(它是主键)的行。在这个特定的代码示例中,我们会将“model”列更新为“Civic”。
-
- //Our MySQL connection details.
- $host = 'localhost';
- $user = 'root';
- $pass = '';
- $database = 'test';
-
- //PDO options. These are optional.
- $options = array(
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_EMULATE_PREPARES => false
- );
-
- //Connect to MySQL and create our PDO object.
- $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options);
-
- //Our UPDATE SQL statement.
- $sql = "UPDATE `cars` SET `model` = :model WHERE id = :id";
-
- //Prepare our UPDATE SQL statement.
- $statement = $pdo->prepare($sql);
-
- //The Primary Key of the row that we want to update.
- $id = 90;
-
- //The new model value.
- $model = 'Civic';
-
- //Bind our value to the parameter :id.
- $statement->bindValue(':id', $id);
-
- //Bind our :model parameter.
- $statement->bindValue(':model', $model);
-
- //Execute our UPDATE statement.
- $update = $statement->execute();
对上述代码的深入分析:
进一步推荐阅读 PDO 和 MySQL: