How can PHP be used to update data in a database using a form?
To update data in a database using a form, you can create an HTML form that allows users to input the data they want to update. When the form is submitted, you can use PHP to retrieve the form data and update the corresponding record in the database using SQL queries.
<?php
// Connect to the database
$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);
}
// Retrieve form data
$id = $_POST['id'];
$newData = $_POST['new_data'];
// Update data in the database
$sql = "UPDATE table_name SET column_name = '$newData' WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close database connection
$conn->close();
?>
Related questions
-
CSV file data import security
-
SELECT * mysql_fetch_row database queries
-
filemtime time PHP script