I have a form set up on a webpage and when data is entered the database returns results with no problems. The problem I have is if a user leaves the form box empty and hits enter then the whole database of results is diplayed. How can I give an error message if nothing is entered in the search box ? <form action="/results.php" method="post"> <div align="center"> <input type="text" name="search"> <br> <input type="submit"> </div> </form> Code (markup):
I think the code below would work, basically it will check for the blank field and display a message. You should name your "Submit" input so you can check if the user hit the "Submit" button or not and results.php will only be executed if the user use the "Submit" button.
<form action="/results.php" method="post"> <div align="center"> <input type="text" name="search"><br/> <input type="submit" name="submit"> </div> </form> <?php $search = $_POST['search']; if ($_POST['submit']) { if (empty($search) ){ echo " Your left this field blank "; }else { //do something here } } ?>
Should be placed on top, not bottom: if($_POST['submit'] == NULL){ if($_POST['search'] == NULL){$message = 'Please enter search term.';} if($message == NULL){ //Do your work } } //Display message anywhere you want on screeen PHP: Peace,