PHP search box - Display search correctly - php

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']);

That you are vulnerable to sql injection. You should use mysqli_ or pdo. For instance you can use mysql_real_escape_string() to avoid this [Though it is not recommended].
$searchq = mysql_real_escape_string($_POST['search']);
Edited: If you sanitize your input and it returns empty string (""), than your query will be :
SELECT * FROM users WHERE firstname LIKE '%%' OR lastname LIKE '%%'
Which will always prints out the whole database content. So check your input variable $searchq after sanitize. If it contains anything than you can perform your query like that:
if(strlen($searchq) > 0)
{
//run query
}
else{
//error message
}

Related

php keyworks search do not works

i want to retrieve data in database by using search engine i create.
it pass the search keywords from testseach.php to searchTitle.php.
here is my code for test seach.php
>!DOCTYPE html>
<html>
<head><title></title>
</head>
<body>
<form action="searchTitle.php" method="GET" class="formright">
<input type="text" name="keywords" placeholder="Search">
<input type="submit" value="search">
</form>
</body>
</html>
here is my searchtitle.php which pass the keywords from testsearch.
<? php
require_once 'database_conn.php'
//collect search title
if(isset($_GET['keywords'])){
$searchq = $_GET['keywords'];
$searchq = preg_replace("#[^a-z]#i" , "", $searchq);
$query = mysql_query("SELECT eventTitle FROM te_events where eventTitle LIKE '%searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count==0){
echo "<p>There was no search result!</p>\n";
}
else{
while ($row = mysql_fetch_assoc($query)){
$title = $row['eventTitle'];
$id = $row['eventID'];
echo "<p>$title</p>\n";
}
}
}
?>
however, it shows this error
There was no search result! \n"; } else{ while ($row =
mysql_fetch_assoc($query)){ $title = $row['eventTitle']; $id =
$row['eventID']; echo " $title
\n"; } } } ?>
i pretty sure that my database connection is working and i don't see any typo in my code.
can anyone tell me what's is my problem?
There are some mistake
1)$query = mysql_query("SELECT * FROM countries",$connection) or die("could not search!");
In mysql_query you add connection variable
please refer syntax as per php documentation
2) You use $count = mysqli_num_rows($query); for get number of raw but you use mysql_num_rows instead of mysqli_num_rows
OR
Please check php version and that compatible with mysql or mysqli
please check it also because that may cause that type of issue also
this answer may be help you.

How to style an output command in php

Hi guys so i am playing around with PHP. i hae a html page which has a list of recipes which have been styled in a div etc. I then have anther page which is a php page which i would like to return the same div with the styles applied. So far all i have manged to do is return normal text.
The normal HTMl is :
Example
My php search code :
I am sure its in this line $output .= '<div>'.$rN.'</div>'; where i am suppose to change the divs but i have tried everything and is getting errors. Any help on this would be great.
Again just so people undertand. The fiddle example is what i want it look like when its retruned. So far those it just looks like normal text. I just need to understand how to call the divs
Just apply the same div that you have and apply the fetched values doing it inside the while block.
Concatenate the values when necessary:
<?php
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM recipe WHERE recipeName LIKE '%$searchq%' OR recipe_ing1 LIKE '%$searchq%' ") or die("Could not search.");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was mo match!';
} else {
while($row = mysql_fetch_array($query)){
$rN = $row['recipeName'];
$output .= '
<div class="panel panel-default">
<div class="panel-heading"><b>' . htmlentities($rN, ENT_QUOTES) . '</b></div>
</div>
';
}
}
}
?>
<form action = "search.php" method = "post">
<input type = "text" name = "search" placeholder = "Search for recipes..."/>
<input type = "submit" value = ">>" />
</form>
<?php echo $output; ?>
Just add a class to the div. You can then reuse this class on any element to use the same style.
$output .= '<div class="your-style-class">'.$rN.'</div>';

How do I make a list with links?

Im making a list with names and links to full info about them. So, I've got simple search engine, which searching by the names or specific numbers. I use $_SESSION to get id of the people. The problem is, when there are more than 1 name and Im moving to the page of specific person appears the page of the last person in the list!
So, code of the search engine is:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9_a-z A-Z]#i","",$searchq);
$query = mysql_query("SELECT * FROM contract WHERE name LIKE '%$searchq%' OR student_code LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no such results!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$student_code = $row['student_code'];
$_SESSION['users_id'] = $row['users_id'];
$output = '<table border ="1"><tr><td>'.$name.' '.$student_code.'
</td>
<td>
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
</form>
</td>
</tr>
</table><br \>
And another script in the page file:
$users_id = $_SESSION['users_id'];
$result = mysql_query("SELECT * FROM contract WHERE users_id = $users_id");
while($myrow = mysql_fetch_array($result)){
$output1 =
The way I understood your question is that you have two pages. One page that does the search, and another page that show the "more info" about a specific result.
What you're basically doing in the search is this:
Let's assume you have three results that got Id 1,4,7.
This is what's going to happen in your while loop
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 1)
Prepare the first result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 4)
Prepare the second result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 7)
Prepare the third result
As you can see you're always overwriting the session key and therefore only the last one will be available when you get to the "cont.php" page (where I'm guessing the other code is?)
One simple solution would be to bake the id into the form and send it along in the request to the cont.php page. Something like this:
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
<input type="hidden" name="user_id" value="' . $row['users_id'] . '">
</form>
And then in the cont.php you simply change this:
$users_id = $_SESSION['users_id'];
to this
$users_id = $_POST['users_id'];
Hope that helps :)

HTML search box to pick up values in a table

Okay this is abit hard to explain but I currently have a website where I'm using PHP and MySQL to pull tables into the web pages and display them. I've been able to make a search function to look for specific values in the table. I'll show you my code.
<!DOCTYPE php>
<html>
<head>
<link rel="stylesheet" href="style.php" media="screen">
</head>
<body>
<a id="TableButton" href="/Test.php">Items Table</a>
<a id="Clear" href="index.php">Clear Search</a>
<center>
<form method="GET" id="SearchPerson">
<select name="Drop" id="Select">
<option value="FirstName">First Name</option>
<option value="Surname">Surname</option>
<option value="MobileNumber">Mobile Number</option>
<option value="Code">Code</option>
<option value="TeamGroup">Team Group</option>
<option value="Home">Home</option>
</select>
<input type="text" name="Box">
<input type="submit" value="Search">
</form>
</center>
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "Database";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
if($_REQUEST['Drop']=='MobileNumber') {
$MobileNumber = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE MobileNumber = $MobileNumber";
}
elseif($_REQUEST['Drop']=='Code') {
$Code = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Code = '$Code'";
}
elseif($_REQUEST['Drop']=='TeamGroup') {
$TeamGroup = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE TeamGroup = '$TeamGroup'";
}
elseif($_GET['Drop']=='FirstName') {
$FirstName = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE FirstName = '$FirstName'";
}
elseif($_GET['Drop']=='Surname') {
$Surname = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Surname = '$Surname'";
}
elseif($_REQUEST['Drop']=='Home') {
$Home = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Home = '$Home'";
}
else{
$query = "SELECT * FROM Person";
}
print "<center id=Title>Person Table</center>";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<center><table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $key=>$value) {
if($key=='MobileNumber'){print "<td><a href='/Test.php?MobileNumber=$value'>$value</a></td>";}
elseif($key=='TeamGroup'){print "<td><a href='/Test.php?TeamGroup=$value'>$value</a></td>";}
elseif($key=='Group'){print "<td><a href='/Test.php?Home=$value'>$value</a></td>";}
else{print "<td>$value</td>";}
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table></center>';
}
else {
echo "No People found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</body>
</html>
Problem is even though I've got the search working it only works if I have the full values whereas i want it so say that i put part of someone mobile number in then itll display the mobile numbers that have those parts of the value in it. For example say that a few people had a mobile number starting with 0783 and I type that into the search box I want it to show up all people with 0783 in their mobile number.
What you are looking for is "SELECT * FROM Person WHERE MobileNumber LIKE '%".$_POST['MobileNumber']."%'", which will look for any string that contains the string you want, but may also be longer on either side. For example, "foo" will return the rows with values "foobar", "barfoo", "barfoobar" and of course "foo", but not "fo".
The % is a wildcard here, which means that you can also do something like "SELECT * FROM Person WHERE MobileNumber LIKE '".$_POST['MobileNumber']."%'" if you specifically want to return rows with values starting with your string ("foobar", but not "barfoo" in our example above).
Please also note the " and '.
Also:
Don't use mysql_query. It's depreciated and will be removed in future versions of PHP. Use PDO or mysqli instead.
Your code is definitely not safe. At least use prepared statements to prevent injection. I would advise against using addslashes as it is very prone to resulting in double escapes if you are not paying attention, and as far as you may also want to go the magic_quotes, be aware it is not portable and may cause you trouble if you rely solely on this. Use mysql_real_escape_string instead, as it is very mysql-oriented and specific.

Why isn't this form returning results?

I have just started trying to learn PHP and MYSQL and have been following some tutorials for creating a webpage search engine, but have been experience an issue wherein when i submit the form the results aren't returned, i have no idea as to where the problem lies or where to try and troubleshoot it, so it thought it'll be worth a shot to post my problem here. Hopefully someone can help me out, thanks in advance.
PHP
<?php
mysql_connect("localhost","root","123")or die("Could not connect to Db");
mysql_select_db("members") or die("Could not find db");
if(isset($_POST['submit'])){
$searchq = $_POST['submit'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("Select * FROM memberlist WHERE Fname LIKE '%$searchq%' OR Lname LIKE '%$searchq%' ") or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output = "No results were found, sorry.";
}
else{
while($row = mysql_fetch_array($query)){
$firstname = $row['Fname'];
$lastname = $row['Lname'];
$output .= "<div>".$firstname." ".$firstname."</div>";
}
}
}
?>
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="searchfname" placeholder="Enter first name">
<input type="text" name="searchlname" placeholder="Enter last name">
<input type="submit" name="submit" value="Submit">
</form>
<?php print($output);?>
</body>
</html>
You can use $_POST['submit'] to check if the form was submitted, but it does not hold all the form values.
You can access the separate form values by their respective name.
So use $_POST['searchfname'] for the value in the first textbox and $_POST['searchlname'] for the second.
Your code should read more like this;
$searchqf = $_POST['searchfname'];
$searchql = $_POST['searchlname'];
$searchqfreplace = preg_replace("#[^0-9a-z]#i","",$searchqf);
$searchqlreplace = preg_replace("#[^0-9a-z]#i","",$searchql);
$query = mysql_query("Select * FROM memberlist WHERE Fname LIKE '%$searchqf%' OR Lname LIKE '%$searchql%' ") or die(mysql_error());
$count = mysql_num_rows($query);
Notice that this way of composing queries is very insecure and vulnerable for SQL injection.
You're also asking for a way to troubleshoot. You probably want to look into echo and print_r.
You have assigned the $searchq variable to your submit button.
Change this line
$searchq = $_POST['submit'];
to
$searchq = $_POST['searchfname'];
or
$searchq = $_POST['searchlname'];
or both:
$searchq = $_POST['searchfname'].$_POST['searchlname'];
you cannot use $searchq = $_POST['submit']; since no value is being posted whose name is submit
you must use any of the following....
$searchq = $_POST['searchfname'];
or
$searchq = $_POST['searchlname'];
In your code you are searching for 'submit' value instead of values from form.
Replace $searchq = $_POST['submit']; with:
$searchq = $_POST['searchfname'];
$searchq2 = $_POST['searchlname'];
and query:
Select * FROM memberlist WHERE Fname LIKE '%$searchq%' OR Lname LIKE '%$searchq2%'
Firstly,
either search with searchfname or with searchlname or both.
Secondly, modify like this
after $count = mysql_num_rows($query);,
if($count == 0){
$output = "No results were found, sorry.";
}
else{
$output = '';
while($row = mysql_fetch_array($query)){
$firstname = $row['Fname'];
$lastname = $row['Lname'];
$output .= "<div>".$firstname." ".$firstname."</div>";
}
Thirdly, Use print $output in the Second page(where database is fetched) and not in First page(Page with FORM).
If you want to show result in the First page, use jQuery/Ajax function

Categories