How to update records in a database using PDO in PHP?

To update records in a database using PDO in PHP, you can follow these steps:

  1. 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(); }
  2. 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";
  3. Prepare the query:

    $stmt = $pdo->prepare($sql);
  4. Bind the values to the placeholders in the query:

    $stmt->bindParam(':value1', $value1); $stmt->bindParam(':value2', $value2); $stmt->bindParam(':id', $id);
  5. 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.