PHP MySQL Update Data: Secure and Dynamic Methods Using MySQLi & PDO

Last updated 3 months, 3 weeks ago | 307 views 75     5

Tags:- PHP

Introduction: Why PHP MySQL Update Queries Matter

In dynamic web applications, data isn't static. Users may:

  • Change their profile info

  • Edit product details

  • Update blog content

The SQL UPDATE command is essential for modifying existing records in a database. But doing so securely and efficiently requires attention to query structure, user input validation, and SQL injection prevention.

In this article, we’ll explore how to safely update MySQL data using PHP, with examples using both MySQLi and PDO, complete with best practices and practical tips.


SQL UPDATE Syntax Overview

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

⚠️ Always include a WHERE clause to avoid updating all records.


Updating Data Using PHP MySQLi

✅ Example 1: Basic MySQLi UPDATE Query

<?php
$conn = new mysqli("localhost", "root", "", "test_db");

// Update user's name where ID is 1
$sql = "UPDATE users SET name='John Doe' WHERE id=1";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully.";
} else {
    echo "Error: " . $conn->error;
}

$conn->close();
?>

MySQLi Prepared Statement (Secure)

<?php
$conn = new mysqli("localhost", "root", "", "test_db");

$id = $_POST['id'];
$name = $_POST['name'];

$stmt = $conn->prepare("UPDATE users SET name = ? WHERE id = ?");
$stmt->bind_param("si", $name, $id); // s = string, i = integer

if ($stmt->execute()) {
    echo "User updated.";
} else {
    echo "Update failed.";
}

$stmt->close();
$conn->close();
?>

Prepared statements are crucial for protecting against SQL injection.


Updating Data Using PHP PDO

✅ Basic PDO UPDATE Query

<?php
$pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "UPDATE users SET name='Jane Doe' WHERE id=2";
$pdo->exec($sql);

echo "Record updated.";
?>

PDO Prepared Statement (Safe)

<?php
$pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$id = $_POST['id'];
$email = $_POST['email'];

$stmt = $pdo->prepare("UPDATE users SET email = :email WHERE id = :id");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

if ($stmt->execute()) {
    echo "Email updated.";
} else {
    echo "Failed to update.";
}
?>

✅ Use named placeholders and bindParam() for clarity and security.


Complete Functional Example: Update User from HTML Form (PDO)

<!-- update_user.php -->
<form method="POST" action="update_user.php">
    <input type="hidden" name="id" value="3">
    <label>Update Name:</label>
    <input type="text" name="name" required>
    <button type="submit">Update</button>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
    $stmt->execute([
        ':name' => $_POST['name'],
        ':id' => $_POST['id']
    ]);

    echo "User info updated.";
}
?>

MySQL UPDATE Use Cases

Use Case SQL Example
Update user password UPDATE users SET password='hashed' WHERE id=10
Change order status UPDATE orders SET status='shipped' WHERE id=345
Bulk price update UPDATE products SET price = price * 1.1 WHERE category='electronics'
Set null value UPDATE logs SET error = NULL WHERE id = 88

Tips & Common Pitfalls

✅ Best Practices

  • Use prepared statements to prevent SQL injection.

  • Validate and sanitize all inputs before using them in a query.

  • Always include a WHERE clause to avoid mass updates.

  • Use affected_rows or rowCount() to confirm if the update was successful.

❌ Common Mistakes

Mistake Solution
Missing WHERE clause Always scope updates to specific rows
Not escaping/validating inputs Sanitize and validate $_POST, $_GET
Using quotes for numbers incorrectly Let prepared statements handle data typing
Failing to handle errors or exceptions Use try/catch for PDO or check mysqli->error

Comparison Table: MySQLi vs PDO for UPDATE Queries

Feature MySQLi PDO
Database Support MySQL only Multiple (MySQL, SQLite, etc.)
Query Type Procedural/Object-Oriented Object-Oriented
Prepared Statement Positional only (?) Named or positional
Error Handling Manual ($conn->error) Try/Catch via exceptions

Conclusion: Updating MySQL Data with PHP the Right Way

The UPDATE statement is a core part of any CRUD application. When implemented correctly, it enables dynamic content management and seamless user interactions. The key is to combine security, validation, and readable code to make your update operations robust and maintainable.

Key Takeaways:

  • Use prepared statements to avoid SQL injection.

  • Validate user input before updating.

  • Always include a WHERE clause.

  • Prefer PDO for more flexibility and cleaner syntax.

  • Confirm updates with affected_rows or rowCount().