In the provided code snippet, what improvements can be made to ensure proper data deletion functionality in the database?
The issue with the provided code snippet is that it is vulnerable to SQL injection attacks due to directly inserting user input into the SQL query. To ensure proper data deletion functionality and prevent SQL injection, we should use prepared statements with parameterized queries to securely handle user input.
// Improvements to ensure proper data deletion functionality in the database
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL statement using a parameterized query to delete data
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
// Set the id parameter and execute the statement
$id = $_GET['id'];
$stmt->execute();
// Close the statement and connection
$stmt->close();
$conn->close();
Related Questions
- How can PHP developers optimize the code of a Socket Server to improve performance and efficiency in handling client connections?
- What is the best way to optimize the SQL queries in the script to avoid redundant database calls?
- How can all $_POST variables be intercepted and passed to another page in PHP?