What are the best practices for updating content on a webpage using PHP and MySQL?
When updating content on a webpage using PHP and MySQL, it is important to first establish a connection to the database, retrieve the existing data, allow the user to make changes to the content, and then update the database with the new information. It is also crucial to sanitize user input to prevent SQL injection attacks.
<?php
// Establish connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve existing data
$id = $_GET['id'];
$sql = "SELECT * FROM table_name WHERE id = $id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
// Allow user to make changes to the content
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$new_content = $_POST['new_content'];
// Update database with new information
$update_sql = "UPDATE table_name SET content = '$new_content' WHERE id = $id";
if ($conn->query($update_sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Related Questions
- In what situations should PHP developers consider using concatenation instead of directly inserting variables in strings?
- What are the potential pitfalls of using isset() to check for form input in PHP?
- What are the advantages of using Autoloading in PHP instead of using the require function for including files?