How can an error code be generated and displayed when executing SQL queries in PHP?
When executing SQL queries in PHP, an error code can be generated and displayed by using the mysqli_error() function to retrieve the error message and mysqli_errno() function to retrieve the error code. This information can help in identifying and troubleshooting any issues with the SQL queries being executed.
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check for connection errors
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Execute SQL query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Check for query errors
if (!$result) {
echo "Error: " . mysqli_error($connection);
echo "Error code: " . mysqli_errno($connection);
exit();
}
// Process query results
while ($row = mysqli_fetch_assoc($result)) {
// Process each row
}
// Close the connection
mysqli_close($connection);