Search the Community
Showing results for tags 'quit app on db exception'.
-
Hi all, I have a snippet of code below. It connects to a DB and then calls a function findMail() if all is well. Code: <?php $host = 'localhost'; $user = 'root'; $password = ''; $database = 'test'; // connect try { $con = new mysqli($host,$user,$password,$database); if($con->connect_errno > 0) throw new Exception("Server goof up!"); mysqli_set_charset($con, "utf8"); } catch(Exception $e){ $e->getMessage(); } if(findMail($con)) echo "<br> Hurray !!"; function findMail($con) { try { $query = "SELECT name, email from users"; $stmt=$con->prepare($query); throw new exception("Problem in DB"); if($stmt->execute()) { $stmt->bind_result($name, $email); while ($stmt->fetch()) { $email = htmlspecialchars($email); $name = htmlspecialchars($name); echo $name.' ---- '.$email.'<br>'; } } } catch(Exception $e){ $e->getMessage(); } return true; } ?> The function findMail() executes a query and displays the name and email from the DB, returns and prints Hurray. If there is an exception thrown in the handling of the DB within the function, then the names and emails from the DB are not echoed, the function returns and prints only Hurray!. Now if it is critical that findMail() executes successfully for the program to proceed further. ( print hurray on exiting the function) i.e it is important for the call to DataBase not fail, then how should this exception be handled by the program to gracefully exit the program then and there. ( Not print hurray). Kindly explain by extending the snippet above. Would this be an ideal case for making a call to an error page ( such as 404) on exit to inform the cliet to try again later maybe? Also how can we ensure that any attempts to reload the previous page using a back key be foiled. Thanks loads everyone.
- 4 replies
-
- exception
- db exception
-
(and 1 more)
Tagged with: