What are common mistakes when inserting data into a MySQL database using PHP?
Common mistakes when inserting data into a MySQL database using PHP include not properly sanitizing user input, not using prepared statements to prevent SQL injection attacks, and not handling errors effectively. To solve these issues, always sanitize user input before inserting it into the database, use prepared statements to bind parameters securely, and check for errors when executing queries.
// Example of inserting data into a MySQL database using prepared statements in PHP
// Assuming $conn is the mysqli connection object
// Sanitize user input
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
// Prepare the SQL statement with placeholders
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
// Bind parameters securely
$stmt->bind_param("ss", $name, $email);
// Execute the statement
if($stmt->execute()){
echo "Data inserted successfully";
} else {
echo "Error inserting data: " . $conn->error;
}
// Close the statement and connection
$stmt->close();
$conn->close();