How can PHP developers effectively debug issues related to saving form data in a database?
To effectively debug issues related to saving form data in a database, PHP developers can start by checking for any errors in their SQL queries, ensuring that the form data is being properly sanitized and validated, and confirming that the database connection is established correctly.
<?php
// Assuming $conn is the database connection object
// Sample form data
$name = $_POST['name'];
$email = $_POST['email'];
// Sanitize form data
$name = mysqli_real_escape_string($conn, $name);
$email = mysqli_real_escape_string($conn, $email);
// Validate form data
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Insert data into database
$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $query)) {
echo "Data saved successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
}
?>