Why is my search bar not showing results? - php

I have made a php search bar before, which worked fine. However, I have recently been developing a one-file web app using the jQuery mobile framework. The aim is to be able to search for a certain trade, person or business, but the results are not showing up. If you search, and there are no results, the message in the output variable prints "There are no results" on the page. The code for the search bar is below:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", "$searchq");
$squery = mysql_query("SELECT * FROM users WHERE name LIKE '%$searchq%' OR fname LIKE '%$searchq%' OR lname LIKE '%$searchq%' OR trade LIKE '%$searchq%' LIMIT 10") or die("Could not search");
$counts = mysql_num_rows($squery);
$output = '';
$outputs = '';
if($counts != 0){
while($row = mysql_fetch_array($searchq)){
$ids = $row['id'];
$fnames = $row['fname'];
$lnames = $row['lname'];
$trades = $row['trade'];
$abouts = $row['about'];
$emails = $row['email'];
$numbers = $row['number'];
$names = $row['name'];
$output .= '<div>'.$trades.' '.$ids.'</div>';
}
}else{
$output = 'Sorry there were no results';
}
}
I print this to the page with:
<h1><?php print($output); ?></h1>
It may also be worth noting that the first feature using php (the sign up form) worked perfectly, but the login form on the same page didn't, and neither does the search bar; I am wondering if having different forms on the same page accessing the same database may cause some kind of problem. If anyone requires any more code, just leave a comment. Thank you in advance.

$searchq = preg_replace("#[^0-9a-z]#i", "", "$searchq"); Should be $searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
i guess this would work fine now.
http://se1.php.net/preg_replace last one should be a variable containing a string and not a string it self.

I think you may use == instead of one =. Please make the change and tell me if it works. It should look like this
if($counts ! == 0)

Related

Creating a php search from Mysql database

I am building a bus reservation system using php & mysql.
In here I am trying to input the search field "route" which is fields of the mysql table.
It seems to have problem in searching and printing the results to the page. Please help me out.
<?php
$connect=mysqli_connect("localhost","root","","tsms");
$output ='';
if(isset($_POST['from'])){
$searchq = $_POST['from'];
$query = mysqli_query("SELECT * FROM bus WHERE route='$serchq' ");
$count = mysqli_num_rows($query);
if($count==0){
echo "<script>
alert('No bus services are found');
</script>";
} else {
while($row = mysqli_fetch_array($query)){
$imageData = $row['image'];
$arrival = $row['arrival_time'];
$departure = $row['departure_time'];
$type = $row['bus_type'];
$class = $row['class'];
$name = $row['bus_name'];
$facilities = $row['facilities'];
$reservation = $row['reservation_fee'];
$output = '<div>'.$arrival.''.$departure.''.$type.''.$class.''.$name.''.$facilities.''.$reservation.'</div>';
}
}
}
echo $output;
?>
Not sure where is the problem, but the sql comparison with "=" searches for a perfect match. Try to use the "like" as
SELECT * FROM bus WHERE route like '%$serchq%'
also, do escape the serchq, because you can get hacked this way.
In your search form, do you have a (dropdown) input or a simple text input?
In your sql query, you are searching for an exact match.
Should this be your issue, consider changing "route='$serchq'" to "route LIKE $serchq" for a more broad match. Also the quotes are not necessary around $serch so eliminating them might help.

How to make PHP makes this query

As I am learning PHP, naturally, I decided to create a search feature on my webpage. However I wanted to make mine more unique, so rather than using just a simple html input field as the 'search' field, I created two html select tags which allow the user to select two options and search based upon that. I managed to get the php to generate the search query, however it wasn't the sql query I wanted. My php code managed to generate a query hat looked like this: .com/results.php?option1=london&option2=car whereas ideally I want it to generate something like this: .com/results.php?combinedoptions=london+car
I've researched thoroughly into this and I hate to ask, what may be, a very simple question on this site.
$input = $_GET['input'];
$topic = $_GET['topic'];
$location = $_GET['location'];
$combined = $input . $topic . '' . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%'";
else
$query .= "OR keywords LIKE '%$each%'";
}
You would just split the incoming string. Here's a piece of code:
<?php
$combinedoptions = 'london+car';
$array = explode("+", $combinedoptions);
if (sizeof($array) != 2) { /*problem here*/ echo 'bad parameters'; return; }
$option1 = $array[0];
$option2 = $array[1];
?>
Just using the explode() method. Compiled code.

Issues with Multiple PHP variables in an SQL statement

My problem is i am trying to get 3 variables from the URL, they echo the correct information so i know that my $_GET's are working fine, The first $SC1 and $SC2 both work fine but the 3rd one in the SQL statement Dosnt.
If i replace
$thestatement = ("SELECT * FROM asset_records WHERE a_catagory = '".$SC1."' AND ".$SC2." = '". $SC3 ."' ");
with
$thestatement = ("SELECT * FROM asset_records WHERE a_catagory = '".$SC1."' AND ".$SC2." = 'apple' ");
it works fine but i know $SC3 = apple because i can echo the variable and its apple, please help im pulling my hair out. Heres the rest of the code regarding this.
Note: This is a search function that basis itself on which link people click in my websites menu and takes into consideration when people first click on the website so it displays all items in it.
require ('..\connect_db.php') ;
$SC1 = mysql_real_escape_string($_GET['sc1']); echo $SC1;
$SC2 = mysql_real_escape_string($_GET['sc2']); echo $SC2;
$SC3 = mysql_real_escape_string($_GET['sc3']); echo $SC3;
if ($SC1 && $SC2 && $SC3 = '') {
$thestatement = ('SELECT * FROM asset_records');}
else {;
$thestatement = ("SELECT * FROM asset_records WHERE a_catagory = '".$SC1."' AND ".$SC2." = '". $SC3 ."' ");
}
$result = mysql_query('' .$thestatement. '') or die(mysql_error());
You are emptying $SC3 in the if condition.

PHP Search Query is not working

I am trying to do a search on my website but for some reason my SELECT query is swapping the keyword and name of the column name when it is executed. Below is code for my query:
if(empty($_POST)=== false){
$output = '';
$error = '';
$input = $_POST['search_input'];
$i=0;
if($input){
$keyword = explode(" ", $input);
require ('core/dbconnection.php');
//If a user is logged in check if the user is Admin or Customer.
if(isset($_SESSION['userid'])){
if($admin == 1){
//enter admin code here
}
}else{
//If user is not logged in search items table only.
$search_items = "SELECT * FROM fyp_items WHERE ";
foreach($keyword as $k){
$i++;
if($i == 1){
$search_items .= "name LIKE $k OR description LIKE $k";
}else
$search_items .= " OR name LIKE $k OR description LIKE $k";
}
$item_qry = mysql_query($search_items)or die(mysql_error());
}
}else
$error = '<p class="pageerror">Please enter your search terms.</p>';
The $search_items is concatanating the search query which is then executed by $item_query .
So I searched for "conwerse" and echo'ed out the $search_itemsvariable I got the following:
http://awesomescreenshot.com/0302ft5mc3
However, when I run the query I get this mysql_error...
http://awesomescreenshot.com/0552ft6bb4
Seems like it swaps the keyword and column name when I run the query. My database tables are of type InnoDB> I would much appreciate your help!
First of all, dont use mysql_query as all mysql_ functions are deprecated. Use mysqli or pdo.
Second, escape your keywords with mysql_escape_string();, like
$k = mysql_real_escape_string($k);
Third, your query, when you echo it, needs to look like this:
SELECT * FROM fyp_items WHERE `name` LIKE 'conwerse' OR `description` LIKE 'conwerse';
There is more, but this should get you started.

PHP MySQL query returning NULL

I have a MySQL table that looks like this:
index | tag | posts
-------------------------
1 | cats | 9,10
2 | a cat | 9,10
3 | kitty | 9,10
4 | meow | 9,10
I am trying to just return the row that matches a search query.
I passed the search parameter using a simple ?search=cats.
This is the PHP that I'm using:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print);
However the mysql_num_rows($query) prints 0 and the $print returns NULL. I can check it with ($print == ""), it evaluates to TRUE and mysql_num_rows($query) returns 4.
I tried setting the search query to something that wasn't in the table and it retuned FALSE as expected. I also tried removing the WHERE tag = '$search' and it returns the table like it should.
Is there something I'm overlooking?
Edit
Took everyone's advice and the code I'm using now is:
$search = mysql_real_escape_string($_GET['search']);
var_dump($search); //prints string(4) "cats" just like it should
$queryText = "SELECT * FROM tags WHERE tag = '%".$search."%'";
echo($queryText); //SELECT * FROM tags WHERE tag = '%cats%'
$query = mysql_query($queryText) or die(mysql_error()); //no error
$rows = mysql_num_rows($query); //this returns 0 and I know it should match 1 row
echo('rows: '.$rows);
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print); //empty
Still have the same problem. The mysql_query is retuning NULL instead of the row or FALSE if it doesn't match.
(in the future I will use the mysqli API, but I would like to finnish this project in mysql. thanks for your suggestions and advice)
Try this code now.
Remeber when you want to debug something in PHP the faster way is var_dump not echo. Also you should avoid mysql_api because they are deprecated, use PDO instead PDO on PHP.net
var_dump($_GET); // Just for debuggin if as something
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'");
// echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
var_dump($result);
//$print = $result['posts'];
//echo($print);
Ok so after referring to the above edit you made, here is the solution
Use "LIKE" instead of "=" when using wildcard "%"
So your query now should be
$queryText = "SELECT * FROM tags WHERE tag LIKE '%" . $search . "%'";
[I created the exact same db on my local system and ran the same code you gave, After making the above changes, It runs as expected]
$search = $_GET['search'];
echo $select_query="SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'";
$query = mysql_query($select_query);
echo(mysql_num_rows($query));
while($result = mysql_fetch_array($query))
{
print_r($result);
}
Note:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
That is very dangerouse: It allow sql incersion code to your database. You must always escape all what you get from the client.
$search = mysql_real_escape_string($_GET['search']); //It require open database connection.
Note2:
mysql_query is obsolete, use mysqli instead ;-)
Answer:
If you have not answer, you probable has an error in an other part.
Try
//1) Look if your search has a correct value
var_dump($search);
//2) Replace the query with (just for debugging):
$query = mysql_query("SELECT * FROM tags WHERE tag = 'cats';");
You may also use "tag like '%cats%'" if you want a more flexible search.
If you remove the WHERE tage = '$search', it cannot return the table like it should because your mysql_fetch_array is not in a while loop... but that aside...
// make sure before you execute the code to check that $_GET['search'] is not empty
// start with escaping the search-value (for mysql-injection)
$search = msyql_real_escape_string($_GET['search']);
// changed the query so it searches for tags containing the search value.
// if you would have records with tags "blue cat" and "red cat" it shows them both
// when searching for "cat"
$query = mysql_query("SELECT * FROM tags WHERE tag LIKE '%".$search."%'");
// put the number of rows in a var
$num = mysql_num_rows($query);
// check this var if it's not 0
if ($num != '0'){
while ($row = mysql_fetch_array($query){
echo $row['posts'];
// etc...
}
} else {
// 0 rows found
echo "nothing found";
}

Categories