What are common pitfalls when trying to insert data into a database table using PHP?
Common pitfalls when trying to insert data into a database table using PHP include not properly sanitizing input data, not using prepared statements to prevent SQL injection attacks, and not handling errors effectively. To solve these issues, always sanitize input data using functions like mysqli_real_escape_string, use prepared statements with placeholders for dynamic data, and implement error handling to catch and log any potential issues.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Sanitize input data
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// Prepare and bind SQL statement
$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
if ($stmt->execute()) {
echo "New record inserted successfully";
} else {
echo "Error: " . $mysqli->error;
}
// Close the statement and connection
$stmt->close();
$mysqli->close();