What are common pitfalls when trying to insert data from $_POST into a database using PHP?
Common pitfalls when trying to insert data from $_POST into a database using PHP include not properly sanitizing input data, leaving the application vulnerable to SQL injection attacks, and not validating the data before insertion, leading to potential errors or unexpected behavior. To solve this issue, always sanitize input data using functions like mysqli_real_escape_string() or prepared statements to prevent SQL injection, and validate the data to ensure it meets the required format before inserting it into the database.
// 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($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
// Validate data
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format");
}
// Insert data into the database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
// Close connection
$mysqli->close();