In the provided PHP code snippet, what improvements can be made to enhance the security and efficiency of the database operations?
The provided PHP code snippet is vulnerable to SQL injection attacks as it directly concatenates user input into the SQL query. To enhance security and efficiency, prepared statements should be used to prevent SQL injection and improve query execution performance. Additionally, error handling should be implemented to handle potential database errors gracefully.
// Original code snippet
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "User added successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
```
```php
// Improved code snippet using prepared statements and error handling
$name = $_POST['name'];
$email = $_POST['email'];
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
if ($stmt->execute()) {
echo "User added successfully";
} else {
echo "Error: " . $conn->error;
}
$stmt->close();
$conn->close();