Skip to content
PHP Logo

What are the best practices for handling database operations like deletion in PHP to avoid issues like the one described in the forum thread?

Issue: The issue described in the forum thread is related to improper handling of database operations like deletion in PHP, leading to potential SQL injection vulnerabilities. To avoid such issues, it is crucial to use prepared statements with parameterized queries to sanitize user input and prevent SQL injection attacks. Fix:

php
// Establish 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);
}

// Prepare and bind statement
$stmt = $conn->prepare("DELETE FROM table_name WHERE id = ?");
$stmt->bind_param("i", $id);

// Set parameter values and execute statement
$id = $_POST['id'];
$stmt->execute();

// Close statement and connection
$stmt->close();
$conn->close();