How to deal with errors, warnings, alerts or notices with PHP. You cannot hard code them into a page because at times they wont be needed yet when they are how can they be shown in a simplistic manner?
Lets assume you submit a form and a field was filled in wrong or it had missing data, you can return the user to the page or another page but this time show an alert styled response on the issue/error, here is how.
A function that sorts and returns based on the int
function alert_system($id = 4) { switch ($id) { case 1: return "<div class='alert alert-primary' role='alert'> This is a notice that ...... </div>"; break; case 2: return "<div class='alert alert-warning' role='alert'> This is a warning that ...... </div>"; break; case 3: return "<div class='alert alert-danger' role='alert'> This is an error notice that ...... </div>"; break; default: return ""; } }
1, 2 or 3 will return the alert html whilst 4 or higher returns nothing i.e no issue.
On our form submit page filter to the error and do a redirect with a GET like:
if (!is_numeric($age)){ header("Location: somepage.php?notice=3"); die(); }
Then the “somepage.php” has this code included (along with Bootstrap and the require_once(‘functions.php’);)
<?php if (isset($_GET['notice'])){ $notice_id = $_GET['notice']; } else { $notice_id = ''; } ?> <div class='container'> <div class="row text-center"> <div class="col-lg-12"> <h1>Page heading here</h1> </div> </div> <div class="row text-center"> <div class="col-lg-12"> <?php echo alert_system($notice_id); ?> </div> </div> <div class="row text-center"> <div class="col-lg-6"> <h2>Content</h2> </div> <div class="col-lg-6"> <h2>Content</h2> </div> </div> </div>
It will display the alert notice pending what the issue is. If the ?notice= isn’t set then nothing gets shown as per the function.