How can you update a specific row in a database using PHP?
To update a specific row in a database using PHP, you can use an SQL UPDATE statement with a WHERE clause that specifies the row to be updated based on a unique identifier, such as an ID. You will need to establish a database connection, construct the SQL query with the updated values, and execute the query using a PHP database extension like PDO or MySQLi.
<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Update a specific row in the database
$id = 1; // ID of the row to be updated
$newValue = "Updated Value";
$sql = "UPDATE table_name SET column_name = '$newValue' WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close the database connection
$conn->close();
?>