Cover Image for PHP MySQLi UPDATE
280 views

PHP MySQLi UPDATE

In PHP, you can use MySQLi (MySQL Improved) to update data in a MySQL database table. To perform an UPDATE operation, follow these steps:

  1. Connect to the MySQL Database:
    First, establish a connection to the MySQL database using the mysqli_connect() function, as shown in the INSERT example.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>
  1. Prepare and Execute the UPDATE Query:
    Next, prepare and execute an UPDATE query to modify data in the database table. Use the mysqli_query() function to execute the query.
<?php
// Assuming you have a table named "users" with columns "id", "name", and "email"
$user_id = 1; // The ID of the user you want to update
$new_name = "Jane Doe"; // The new name you want to set for the user

// Prepare the UPDATE query
$sql = "UPDATE users SET name = '$new_name' WHERE id = $user_id";

// Execute the query
if (mysqli_query($conn, $sql)) {
    echo "Record updated successfully.";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>

In this example, we are updating the name of a user with the ID 1 to “Jane Doe.”

  1. Close the Database Connection:
    After executing the query, close the database connection using the mysqli_close() function to free up resources.
<?php
// Close the connection
mysqli_close($conn);
?>

As with the INSERT example, always use proper data sanitization and validation techniques to prevent SQL injection and other security issues. Prepared statements or parameterized queries are safer methods to interact with the database.

Important Note: When building dynamic SQL queries with user input, use prepared statements or escape user input using functions like mysqli_real_escape_string() to prevent SQL injection attacks. Never directly embed user input in the SQL query.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS