PHP Search Query is not working - php

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.

Related

SQL Keyword search

I am trying to create a search Function on my website using PHP and SQL.
I am trying to make it so that when i search for a keyword in it displays items matching the key word
This is my Database
If i was to search "rice chicken" it would return both Davida and roys, i would like it to only return Davids as it matches both words and not roys as roys only matches rice
Thos is my current code.
$search = $_GET['query'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("axamenu");
$query = mysql_query("SELECT * FROM menu WHERE CONTAINS(items,'$.search')");
if(mysql_num_rows($query) >= 1) {
while($a = mysql_fetch_array($query)) {
echo "<a href='".$a['profileurl']."'>".$a['restaurant']."</a><p>".$a['menutype']."</p><hr/>";
}
} else {
echo "Oh no! Nothing was found.";
}
You could make your query in this way
$where = '';
$string = "thi sdas asd";
$search = explode(" ",$string);
if(sizeof($search)>1)
{
$where = "1=1";
foreach($search=>$key as $val){
$where .= "or items like %".$val."%";
}
}
else
{
$where = "items like %".$search[0]."%"
}
$query = mysql_query("SELECT * FROM menu WHERE ".$where);
//rest of your code goes here
Note: Stop using deprecated and insecure mysql_*-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7. Use MySQLi or PDO instead
If you only want davids result as "rice chicken",
you can split your string as rice and chicken and query as
SELECT * from menu WHERE items REGEXP 'rice' AND items REGEXP 'chicken'
you will get only one result
NOTE: using REGEXP can slow down result for bulk data retrieving
$search = $_GET['query'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("axamenu");
$query = mysql_query("SELECT * FROM menu WHERE
items LIKE '%".$search."%'");
if(mysql_num_rows($query) >= 1)
{
while($a = mysql_fetch_array($query))
{
echo "<a href='".$a['profileurl']."'>".$a['restaurant']."</a><p>".$a['menutype']."</p><hr/>";
}
}
else
{
echo "Oh no! Nothing was found.";
}
Try with this and let us if that works.
select * from table_name where items like 'rice%' or items like 'chicken%';

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.

PHP Search Engine no results are returned even if the input matches data in the table

I'm trying to create a search engine for my website where users can enter keywords and the PHP script will search the 'name' and 'description' columns of my fyp_items table. So far I have managed to break down the input to an array of words and am try to execute a SELECT query on my database.
THE ISSUE is that it fails to find the items even if the keyword matches that of the data in the table. Below is my script...I hope someone can help me.
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){
}
}else{
//If user is not logged in search items table only.
$search_items = "SELECT * FROM fyp_items WHERE ";
foreach($keyword as $k){
$k = mysql_real_escape_string($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());
$numrows = mysql_num_rows($item_qry);
if($numrows > 0){
$output = 'found it';
}else
$error = '<p class="pageerror">Sorry, what you were looking for was not found.</p>';
}
}else
$error = '<p class="pageerror">Please enter your search terms.</p>';
I have tested the post by echoing the output and I have also echoed the $search_items variable to get this...
http://awesomescreenshot.com/05c2fwytac
Your help will be much appreciated!
You're building an incorrect query string, that'll be something like
SELECT ... WHERE name LIKE 'foo' OR description LIKE 'foo'
a LIKE comparison without wilcards is pointless. You've functionally got the equivalent of
SELECT ... WHERE name='foo' OR description='foo'
The wildcards allow substring matching in the fields:
SELECT ... WHERE name='%foo%' OR description = '%foo%'
so the word foo can appear ANYWHERE in the field and match. Right now your query will only match if foo is the ONLY thing in either field.
And these sorts of queries are highly inefficient, especially as the number of search terms climbs. You should be suing a fulltext search: https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Advance Searching, PHP & MySQL

I'm trying to create an Advanced Searching form that sort of look like this ;
http://img805.imageshack.us/img805/7162/30989114.jpg
but what should I write for the query?
I know how to do it if there is only two text box but three, there's too many probability that user will do.
$query = "SELECT * FROM server WHERE ???";
What should I write for the "???"
I know how to use AND OR in the query but lets say if the user only fill two of the textbox and one empty. If I write something like this ;
$query = "SELECT * FROM server WHERE model='".$model."' and brand='".$brand."' and SN='".$SN.'" ";
The result will return as empty set. I want the user can choose whether to fill one,two or three of the criteria. If I use OR, the result will not be accurate because if Model have two data with the same name (For example :M4000) but different brand (For example : IBM and SUN). If I use OR and the user wants to search M4000 and SUN, it will display both of the M4000. That's why it is not accurate.
If the user can decide how many criteria he wants to enter for your search and you want to combine those criteria (only those actually filled by the user), then you must dynamically create your SQL query to include only those fields in the search that are filled by the user. I'll give you an example.
The code for a simple search form could look like this:
$search_fields = Array(
// field name => label
'model' => 'Model',
'serialNum' => 'Serial Number',
'brand' => 'Brand Name'
);
echo "<form method=\"POST\">";
foreach ($search_fields as $field => $label) {
echo "$label: <input name=\"search[$field]\"><br>";
}
echo "<input type=\"submit\">";
echo "</form>";
And the code for an actual search like this:
if (isset($_POST['search']) && is_array($_POST['search'])) {
// escape against SQL injection
$search = array_filter($_POST['search'], 'mysql_real_escape_string');
// build SQL
$search_parts = array();
foreach ($search as $field => $value) {
if ($value) {
$search_parts[] = "$field LIKE '%$value%'";
}
}
$sql = "SELECT * FROM table WHERE " . implode(' AND ', $search_parts);
// do query here
}
else {
echo "please enter some search criteria!";
}
In the above code we dynamically build the SQL string to do a search ("AND") for only the criteria entered.
Try this code
<?php
$model="";
$brand="";
$serialNum="";
$model=mysql_real_escape_string($_POST['model']);
$brand=mysql_real_escape_string($_POST['brand']);
$serialNum=mysql_real_escape_string($_POST['serialNum']);
$query=" select * from server";
$where_str=" where ";
if($model == "" && $brand == "" && $serialNum == "")
{
rtrim($where_str, " whrere ");
}
else
{
if($model != "")
{
$where_str.= " model like '%$model%' AND ";
}
if($brand != "")
{
$where_str.= " brand like '%$brand%' AND ";
}
if($serialNum != "")
{
$where_str.= " serialNum like '%$serialNum%' AND ";
}
rtrim($where_str, " AND ");
}
$query.= $where_str;
$records=mysql_query($query);
?>
For those framiliar with mysql, it offers the ability to search by regular expressions (posix style). I needed an advanced way of searching in php, and my backend was mysql, so this was the logical choice. Problem is, how do I build a whole mysql query based on the input? Here's the type of queries I wanted to be able to process:
exact word matches
sub-string matches (I was doing this with like "%WORD%")
exclude via sub-string match
exclude via exact word match
A simple regexp query looks like:
select * from TABLE where ROW regexp '[[:<:]]bla[[:>:]]' and ROW
regexp 'foo';
This will look for an exact match of the string "bla", meaning not as a sub-string, and then match the sub-string "foo" somewhere.
So first off, items 1 and 4 are exact word matches and I want to be able to do this by surrounding the word with quotes. Let's set our necessary variables and then do a match on quotes:
$newq = $query; # $query is the raw query string
$qlevel = 0;
$curquery = "select * from TABLE where "; # the beginning of the query
$doneg = 0;
preg_match_all("/\"([^\"]*)\"/i", $query, $m);
$c = count($m[0]);
for ($i = 0; $i < $c; $i++) {
$temp = $m[1][$i]; # $temp is whats inside the quotes
Then I want to be able to exclude words, and the user should be able to do this by starting the word with a dash (-), and for exact word matches this has to be inside the quotes. The second match is to get rid of the - in front of the query.
if (ereg("^-", $temp)) {
$pc = preg_match("/-([^-]*)/i", $m[1][$i], $dm);
if ($pc) {
$temp = $dm[1];
}
$doneg++;
}
Now we will set $temp to the posix compliant exact match, then build this part of the mysql query.
$temp = "[[:<:]]".$temp."[[:>:]]";
if ($qlevel) $curquery .= "and "; # are we nested?
$curquery .= "ROW "; # the mysql row we are searching in
if ($doneg) $curquery .= "not "; # if dash in front, do not
$curquery .= "regexp ".quote_smart($temp)." ";
$qlevel++;
$doneg = 0;
$newq = ereg_replace($m[0][$i], "", $newq);
}
The variable $newq has the rest of the search string, minus everything in quotes, so whatever remains are sub-string search items falling under 2 and 3. Now we can go through what is left and basically do the same thing as above.
$s = preg_split("/\s+/", $newq, -1, PREG_SPLIT_NO_EMPTY); #whitespaces
for ($i = 0; $i < count($s); $i++) {
if (ereg("^-", $s[$i])) { # exclude
sscanf($s[$i], "-%s", $temp); # this is poor
$s[$i] = $temp;
$doneg++;
}
if ($qlevel) $curquery .= "and ";
$curquery .= "ROW "; # the mysql row we are searching in
if ($doneg) $curquery .= "not ";
$curquery .= "regexp ".quote_smart($s[$i])." ";
$qlevel++;
$doneg = 0;
}
# use $curquery here in database
The variable $curquery now contains our built mysql query. You will notice the use of quote_smart in here, this is a mysql best practice from php.net. It's the only mention of security anywhere in this code. You will need to run your own checking against the input to make sure there are no bad characters, mine only allows alpha-numerics and a few others. DO NOT use this code as is without first fixing that.
You have to provide $model, $brand, $serial which come from your search-form.
$query = "SELECT * FROM `TABLE` WHERE `model` LIKE '%$model%' AND `brand` LIKE '%$brand%' AND `serial` LIKE '%$serial%'";
Also take a look at the mysql doc
http://dev.mysql.com/doc/refman/5.1/en/string-comparison-functions.html
A basic search would work like this:
"SELECT * FROM server WHERE column_name1 LIKE '%keyword1%' AND column_name2 LIKE '%keyword2%' .....";
This would be case for matching all parameters.For matching any one of the criteria, change ANDs to ORs

mysql PHP query question

Ok, i have a problem here...
I am sending values of drop down lists via ajax to this PHP file.
Now I want to search a mysql database using these values, which I have managed to do, BUT, only if I set the values to something...
Take a look:
$query = "SELECT * FROM cars_db WHERE price BETWEEN '$cars_price_from' AND '$cars_price_to' AND year BETWEEN '$cars_year_from' AND '$cars_year_to' AND mileage BETWEEN '$cars_mileage_from' AND '$cars_mileage_to' AND gearbox = '$cars_gearbox' AND fuel = '$cars_fuel'";
now, what if the user doesnt select any "price_from" or "year_from"... The fields are only optional, so if the user doesnt enter any "price from" or "year from", then the user wants ALL cars to show...
Do I have to write a query statement for each case or is there another way?
I do something similar to davethegr8 except I put my conditions in an array and then implode at the end just so I don't have to worry about which conditions got added and whether I need to add extra AND's.
For example:
$sql = "SELECT * FROM car_db";
// an array to hold the conditions
$conditions = array();
// for price
if ($car_price_from > 0 && $car_price_to > $car_price_from) {
$conditions[] = "(price BETWEEN '$cars_price_from' AND '$cars_price_to')";
}
elseif ($car_price_from > 0) {
$conditions[] = "(price >= '$cars_price_from')";
}
elseif ($car_price_to > 0) {
$conditions[] = "(price <= '$cars_price_from')";
}
else {
//nothing
}
// similar for the other variables, building up the $conditions array.
// now append to the existing $sql
if (count($conditions) > 0){
$sql .= 'WHERE ' . implode(' AND ', $conditions);
}
You could simply detect which parameters are missing in your PHP code and fill in a suitable default. eg
if (!isset($cars_mileage_to))
$cars_mileage_to = 500000;
You can build you query, adding the "where" part only if your variables are different from "".
or if you're using mysql 5.x, you can also use subselects:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
don't forget to validate the input. It's trivial with firebug, for example, to inject some tasty sql.

Categories