In the given code snippet, what improvements can be made to enhance the security of database operations?
The given code snippet is vulnerable to SQL injection attacks as it directly concatenates user input into the SQL query. To enhance the security of database operations, we can use prepared statements with parameterized queries. This approach separates the SQL query from the user input, preventing malicious SQL injection attacks.
// Improved code with prepared statements for database operations
// Establish 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 and bind SQL statement
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// Set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john.doe@example.com";
$stmt->execute();
echo "New records created successfully";
// Close statement and connection
$stmt->close();
$conn->close();