How can error handling be improved in the provided PHP script to identify and troubleshoot database insertion failures?
The issue with the current PHP script is that it lacks proper error handling for database insertion failures, making it difficult to identify and troubleshoot issues. To improve error handling, we can implement try-catch blocks around the database insertion code and utilize the mysqli_error() function to retrieve detailed error messages.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Data to insert into the database
$name = "John Doe";
$email = "john.doe@example.com";
// Insert data into the database with error handling
try {
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
throw new Exception("Error: " . $sql . "<br>" . $conn->error);
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
$conn->close();
?>
Keywords
Related Questions
- How can form submissions be handled in PHP to prevent the browser from reloading the script and changing the URL path?
- How can PHP developers ensure proper quoting and formatting when using file_get_contents to send HTTP requests?
- How can the use of dynamic URLs with changing query parameters improve image reloading in PHP?