What steps can be taken to troubleshoot and debug issues with data not being inserted into a database from a PHP form submission?
Issue: If data is not being inserted into a database from a PHP form submission, it could be due to errors in the SQL query, connection to the database, or form submission handling. To troubleshoot and debug this issue, check the SQL query for errors, ensure the database connection is established correctly, and verify that the form submission is capturing and processing data accurately.
// Ensure database connection is established
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Capture form data
$name = $_POST['name'];
$email = $_POST['email'];
// Insert data into database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();