PHP MySQL UPDATE QUERY
To perform an UPDATE
query in PHP using MySQLi in procedural style, follow these steps:
1. Establish a Database Connection
First, you need to connect to the MySQL database using mysqli_connect()
.
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
2. Prepare the UPDATE
Query
Construct the SQL UPDATE
query string. For example, if you want to update the email of a user in a table named users
, your query might look like this:
$sql = "UPDATE users SET email = 'newemail@example.com' WHERE username = 'john_doe'";
3. Execute the Query
Use mysqli_query()
to execute the UPDATE
query.
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
4. Close the Database Connection
After executing the query, close the connection using mysqli_close()
.
mysqli_close($conn);
Full Example
Here’s a complete example demonstrating an UPDATE
query using MySQLi in procedural style:
<?php
// Step 1: Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 2: Prepare the UPDATE query
$sql = "UPDATE users SET email = 'newemail@example.com' WHERE username = 'john_doe'";
// Step 3: Execute the query
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
// Step 4: Close the connection
mysqli_close($conn);
?>
Notes
- Error Handling: Always check if
mysqli_query()
returnsfalse
to handle potential errors in the query execution. - Escaping Strings: To prevent SQL injection, especially when dealing with user input, use
mysqli_real_escape_string()
to escape input values before including them in your query. - Prepared Statements: For better security and to handle dynamic data safely, consider using prepared statements with
mysqli_prepare()
andmysqli_stmt_bind_param()
. This approach helps prevent SQL injection attacks.
Here’s an example using prepared statements for the UPDATE
query:
<?php
// Step 1: Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 2: Prepare the UPDATE query
$stmt = mysqli_prepare($conn, "UPDATE users SET email = ? WHERE username = ?");
// Bind parameters
mysqli_stmt_bind_param($stmt, "ss", $email, $username);
// Set parameters and execute
$email = 'newemail@example.com';
$username = 'john_doe';
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt) > 0) {
echo "Record updated successfully";
} else {
echo "No record updated or an error occurred";
}
// Close the statement and connection
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>