To update records in a database using PDO in PHP, you can follow these steps:
Connect to the database:
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Construct an SQL UPDATE query with placeholders for the data you want to update:
$sql = "UPDATE your_table SET column1 = :value1, column2 = :value2 WHERE id = :id";
Prepare the query:
$stmt = $pdo->prepare($sql);
Bind the values to the placeholders in the query:
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->bindParam(':id', $id);
Execute the query:
$stmt->execute();
Here's a complete example that updates the name and email of a user with a specific ID:
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$id = 1;
$name = 'John Doe';
$email = '[email protected]';
$sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':id', $id);
$stmt->execute();
Make sure to replace the placeholders (your_database
, your_username
, your_password
, your_table
, column1
, column2
, id
, value1
, value2
) with the appropriate values for your database and table.