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
- How important is it for PHP beginners to have a basic understanding of JavaScript when working with APIs like Laut.FM?
- How can dynamic IP addresses from ISPs like Telekom impact email delivery when using PHP to send emails?
- How can the issue of an undefined index in $_GET be resolved when trying to retrieve data from a database in PHP?