How can you optimize the code provided to improve the user experience and ensure smooth functionality?
The issue with the current code is that it is not properly sanitizing user input, which can lead to security vulnerabilities such as SQL injection. To optimize the code and improve user experience, we should use prepared statements to prevent SQL injection attacks and ensure smooth functionality.
// Connect to the database
$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 users (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// Set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();