In PHP dynamic web application development, database operation is a very important skill. PDO is an implementation of the PHP Data Object (PHP Data Object) extension, which can operate various database systems in an object-oriented manner in PHP.
In database operations, modifying data is an operation we often need to use. Below we will demonstrate how to modify database data through PHP PDO.
First, we need to connect to the database. The example of using PDO to connect to the MySQL database is as follows:
// 数据库连接信息 $host = "localhost"; $dbname = "test"; $username = "root"; $password = "password"; // 数据库连接 try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully\n"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
We can modify$host
,$dbname
,$username
, ## according to the actual situation. The value of #$password.
userstable, which contains a user with
id1, and we want to modify the user's name to "Tom".
// 修改数据 $stmt = $conn->prepare("UPDATE users SET name=:name WHERE id=:id"); $stmt->bindParam(':name', $name); $stmt->bindParam(':id', $id); $name = "Tom"; $id = 1; $stmt->execute();
UPDATEin the SQL statement indicates updating data,
SETis followed by the fields and values that need to be modified, and
WHEREconstraints.
preparemethod to prepare SQL statements, use the
bindParammethod to bind parameters, and use
executeMethod to execute SQL statements.
// 数据库连接信息 $host = "localhost"; $dbname = "test"; $username = "root"; $password = "password"; // 数据库连接 try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully\n"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } // 修改数据 $stmt = $conn->prepare("UPDATE users SET name=:name WHERE id=:id"); $stmt->bindParam(':name', $name); $stmt->bindParam(':id', $id); $name = "Tom"; $id = 1; $stmt->execute(); echo "Data updated successfully\n"; // 断开数据库连接 $conn = null;
The above is the detailed content of How to modify database data with PHP PDO. For more information, please follow other related articles on the PHP Chinese website!