How to update data in a database with PHP and MySQL
To update data in a MySQL database using PHP, you need to use the “UPDATE” SQL statement. Here’s a basic example using PHP’s mysqli library:
// Connect to the database $conn = mysqli_connect("localhost", "username", "password", "dbname"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Update a specific row $sql = "UPDATE users SET email='newemail@example.com' WHERE id=1"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } // Close connection mysqli_close($conn);
In the above example, we’re updating the email of a user with an ID of 1. The “SET” clause specifies the new email that we want to update, while the “WHERE” clause identifies which row(s) to update based on some condition.
You can also use variables in your update statement to make it more dynamic. Here’s an example that updates the email of a user based on a form submission:
// Get form data $id = $_POST['id']; $new_email = $_POST['email']; // Connect to the database $conn = mysqli_connect("localhost", "username", "password", "dbname"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Update the user's email address $sql = "UPDATE users SET email='$new_email' WHERE id=$id"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } // Close connection mysqli_close($conn);
In this example, we’re getting the user’s ID and new email from a form submission using the $_POST superglobal. We’re then using those values to update the corresponding row in the database.
For more information on updating data in MySQL with PHP, check out the following resources:
– w3schools PHP MySQL Update
– PHP.net MySQLi Statements
Written by: Maria Jensen 14-06-2023 Written in: PHP tutorials