How can PHP be used to display database error messages when performing operations like inserting data into a MySQL or MariaDB table?
When performing operations like inserting data into a MySQL or MariaDB table using PHP, it is important to handle database errors properly to provide meaningful feedback to users. One way to display database error messages is by using the mysqli_error() function in PHP. This function retrieves the error message from the most recently executed MySQL function.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform insert operation
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($mysqli->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $mysqli->error;
}
// Close connection
$mysqli->close();
Keywords
Related Questions
- Are there alternative methods to using arrays for storing and manipulating data in PHP?
- Are there limitations or bugs in the ExcelWriter package that could be causing Excel files generated by PHP to have unreadable content errors?
- Are there any specific PHP libraries or tools that are recommended for implementing automatic loading of list items while scrolling?