In PHP and MySQL, updating data in a database table is a common operation. Here’s how you can update data in a MySQL database using PHP.
Assuming we have a table called “users” with the following fields:
- id (integer)
- name (string)
- email (string)
- age (integer)
To update data in the table, we use the SQL UPDATE
statement.
Here’s an example of updating the name and age of a user with a specific id:
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'mydb');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL query to update a user by id
$sql = "UPDATE users SET name = 'John Doe', age = 25 WHERE id = 1";
if (mysqli_query($conn, $sql)) {
echo "User updated successfully";
} else {
echo "Error updating user: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>
In the example above, we first connect to the database using mysqli_connect()
. We then define the SQL statement to update the user with id=1, using the UPDATE
statement and the WHERE
clause to specify the user to be updated. We execute the SQL statement using mysqli_query()
, and check if it was successful. If there was an error, we print an error message using mysqli_error()
. Finally, we close the database connection using mysqli_close()
.
You can modify the SQL query to update data based on different criteria. For example, to update the email of a user with name=”Jane Doe”, you can use the following SQL query:
UPDATE users SET email = 'jane@example.com' WHERE name = 'Jane Doe'
And the PHP code to execute this query would look like this:
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'mydb');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL query to update the email of a user with name="Jane Doe"
$sql = "UPDATE users SET email = 'jane@example.com' WHERE name = 'Jane Doe'";
if (mysqli_query($conn, $sql)) {
echo "User updated successfully";
} else {
echo "Error updating user: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>