I have been working on exceptions thrown by php - mysqli & created this snippet below that tries to check a few times to see if a temp glitch has caused the database to fail. if so, it tries to recover. If it cannot then it quits/ ends.
Now while the logic is fine, I cannot find out why the echo statements do not occur at regular intervals as they should. Only towards the end (depending upon how the exception is thrown in the findMail() function), the output is spewed & correctly so. The throw new exception line can be changed to fail at all times or to pass the last time around. It is set to pass the last time round in the snippet. Would be great if someone can point to me why the echo is not displaying the output as it should at intervals.
Further I am not sure if this is a good or a bad idea in production. Any feedback on this is very welcome. Thanks to all.
The code Snippet:
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test';
// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
try
{
$con = new mysqli($host,$user,$password,$database);
if($con->connect_error)
{
throw new Exception("Goof Up");
}
mysqli_set_charset($con, "utf8");
}
catch(Exception $e)
{
echo $e->getMessage();
exit;
}
// All well so far
$cnt = 0;
if(findMail($con,$cnt)) echo "<br> Hurray !!";
function findMail($con,$cnt)
{
try
{
echo $cnt++."<br>";
$query = "SELECT name, email from users";
$stmt=$con->prepare($query);
if($cnt < 3 ) throw new exception($cnt);
if($stmt->execute())
{
$stmt->bind_result($name, $email);
while ($stmt->fetch())
{
$email = htmlspecialchars($email);
$name = htmlspecialchars($name);
echo $name.' ---- '.$email.'<br>';
}
}
}
catch(Exception $e)
{
$cnt = (int)($e->getMessage());
// echo $cnt;
if($cnt === 4) { echo "Ending"; exit();}
sleep(5);
findMail($con,$cnt);
}
return true;
}
?>