My .php includes quote.php followed with the rest of the page. When the connection fails, I see "Fatal error: Uncaught mysqli_sql_exception: ----- include_once('C:\xampp\htdocs...') ---- and the remainder of the page does not load.
What must I do to display an error message, THEN the rest of my page?
CodePudding user response:
Your situation is a rare case when using a try catch is justified.
All you need to do it wrap the include in a try-catch:
try {
require 'quote.php';
} catch(\Throwable $e) {
error_log($e); // for the future inspection
echo "Problem loading this part of page";
}
That's all. The error message will be shown and the rest of the page will be loaded.
But of course this approach should only be used when the content from quote.php is optional. In the every other case there must be no local try-catch but a site-wide error handler.
CodePudding user response:
Using @O. Jones idea and some nasty GoTO's, this does the job. The warnings and error are still displayed. The rest of the page is able to load now.
<?php
mysqli_report(MYSQLI_REPORT_OFF);
$dbServer = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project_01";
$conn = mysqli_connect($dbServer, $dbUsername, $dbPassword, $dbName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to the MySQL Database: ";
goto end;
}
$sql = "SELECT * FROM tbl_quotes";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rand = random_int(1,$rowcount);
} else {
echo "No records were found";
goto end;
}
$sql = "SELECT quote, credit FROM tbl_quotes where ID = $rand";
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
printf ("%s" . " - " . "(%s)\n", $row[0], $row[1]);
}
// Free result set
mysqli_free_result($result);
}
end:
?>
Thanks to all who looked.
CodePudding user response:
php / msqli is throwing exceptions. You need to write exception handler code (try { } catch (mysqli_sql_exception $e) { }
code in your program to handle errors.
As a quick and sleazy workaroud for the current state of your code you can put this line of code at the top of your page. give this line of code
mysqli_report(MYSQLI_REPORT_OFF):;
This will suppress php exceptions and warnings, and let you rely completely on mysqli_connect_errno()
to catch your errors.