The search fusion works correctly but if I press submit with nothing in the search bar it shows all the data. how would I get a message to show up saying that nothing has been entered into the search bar ?.I am new to PHP.
<?php
$mysql_host="host";
$mysql_database="database";
$mysql_user="username";
$mysql_password="password";
$dbconnect=@mysql_connect($mysql_host, $mysql_user, $mysql_password);
// trys to connect to the database
if (!$dbconnect) {
exit("An error has occurred - could not connect to the database.");
// if couldn't connect, let the user know
}
if(!mysql_select_db($mysql_database)) {
exit("An error has occurred - Could not select the database.");
//if couldn't select db, let the user know
}
$output = '';
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM people WHERE firstname LIKE '%" . $searchq . "%' OR surname LIKE '" . $searchq . "';");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while ($row = mysql_fetch_array($query)) {
$fname = $row ['firstname'];
$lname = $row ['surname'];
$id = $row ['id'];
$output .= '<div>'.$fname.' '.$lname.'</div>';
}
}
}
?>
<html>
<head>
<title>search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search here......." />
<input type="submit" value="submit" />
</form>
<?php print("$output");?>
</body>
</html>
If you want to avoid all of the results that are showing up when you submit the form, you need to check at what is being submitted in the text input.
Right now, if $searchq == ""
then you're SQL query will search: WHERE firstname LIKE '%%'
which is just a wildcard on anything.
In order to fix this, add $_POST['search'] != ""
to the initial condition.
<?php
// Make sure to only perform the search and show the results if there's something to search for
if(isset($_POST['search']) && $_POST['search'] != "") {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM people WHERE firstname LIKE '%" . $searchq . "%' OR surname LIKE '" . $searchq . "';");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while ($row = mysql_fetch_array($query)) {
$fname = $row ['firstname'];
$lname = $row ['surname'];
$id = $row ['id'];
$output .= '<div>'.$fname.' '.$lname.'</div>';
}
}
}
Now it will only search when the form has been submitted with a string to search with!