I'm building a search function for a website. What I don't like is that if I enter some special symbols Like < or > or % or others in the search box it prints out the whole database content even if there are no such symbols in the search entries. What should I do so the search outputs only entries which contains the special symbol. And not the all entries which database contains.
Code:
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());;
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM users WHERE firstname LIKE '%$searchq%' OR lastname LIKE '%$searchq%'") or die("Could not search!");
$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['lastname'];
$id = $row['id'];
$output .= '<div>'.$fname.' '.$lname.'</div>';
}
}
}
?>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="top">
<form action="search3.php" method="post">
<input type="text" name="search" placeholder="Search here" />
<input type="submit" value=">>" />
</form>
</div>
<div id="top2">
<?php print("$output"); ?>
</div>
</body>
</html>
Edited. I tried to sanitize, it still don't work as planed.
function sanitize($data) {
return htmlentities(strip_tags(mysql_real_escape_string($data)));
}
$searchq = sanitize($_POST['search']);