How can error reporting in PHP be utilized to troubleshoot issues with database insertion?
When troubleshooting database insertion issues in PHP, error reporting can be utilized to identify any errors that occur during the insertion process. By enabling error reporting and displaying error messages, developers can pinpoint the exact cause of the problem, such as syntax errors, connection issues, or data validation problems.
// Enable error reporting for debugging purposes
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Code for database insertion
$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);
}
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();