How can errors in PHP scripts, such as not saving form data to a database, be effectively debugged and resolved?
To debug and resolve errors in PHP scripts, such as not saving form data to a database, you can start by checking for syntax errors, ensuring database connection is established correctly, and validating form input data before inserting it into the database. Additionally, you can use error reporting functions like error_log() or var_dump() to identify the root cause of the issue.
// Assuming you have established a database connection
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate and sanitize form data
$name = htmlspecialchars($_POST["name"]);
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
// Insert data into database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $sql)) {
echo "Data saved successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}