Search suggestion box inputs space in front of search query - php

We have a problem with our search suggestions. Everytime we click on a suggestion at our website, it puts a space in front of the search query, which causes the query to fail.
The code that we use for the suggestions is this:
$query = $db->query("SELECT DISTINCT productnaam FROM product WHERE merk LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->merk.' '.$result->productnaam.'\');">'
.$result->merk.' '.$result->productnaam.''.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';

Try out with trim()
$queryString = trim($queryString);
The trim() function removes whitespaces and other predefined characters from both sides of a string.

try the trim() function as Sameera Thilakasiri specified below and also update your query to something like "SELECT DISTINCT productnaam FROM product WHERE merk LIKE '%$queryString%' LIMIT 10" The percent sign on both sides will ensure that your query will select records that contain your input as opposed to records that start with your input.
bellow is some further explanation on the SQL LIKE condition that might help you out
// This query will look for records that start with "sa"
select * from table where name like 'sa%'
// This query will look for records that contain "sa"
select * from table where name like '%sa%'
// This query will look for records that end with "sa"
select * from table where name like '%sa'
hope that helps!

Related

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

search a single word in a column

I want to fetch the one word out of the 4 words in the column category. For example I search for Buffet and the restaurant that has Buffet will display. This is my code so far and unfortunately it doesn't work.
HomeController
public function searchresto(){
$searchinfo = $_POST['searchinfo'];
$this->load->model('RestoModel');
$restaurantinfo['restaurantinfo']=$this->RestoModel>searchRestaurant($searchinfo);
$this->load->view('pages/searchDisplay',$restaurantinfo);
}
RestoModel
public function searchRestaurant($searchinfo){
$sql = "SELECT * FROM restaurants WHERE restoname = '$searchinfo' OR restocuisines = '$searchinfo' OR category = '$searchinfo'";
$result = $this->db->query($sql);
$result = $result->result('array');
return $result;
}
First, sanitize user input. Never query the database directly from the user input, as this may cause SQL Injection.
After sanatizing the user input, try using the LIKE function.
For example:
SELECT 'Breakfast, Lunch, Dinner, Buffet, Snack' LIKE '%Lunch%' would output 1.
SELECT 'Breakfast, Lunch, Dinner, Buffet, Snack' LIKE '%NonExistantCategory%' would output 0.
Try changing your query to SELECT * FROM restaurants WHERE category LIKE '%$searchinfoSanatized%', where $searchinfoSanatized is the input that has been filtered/escaped.
Also, I believe you are forgetting a - after RestoModel: $restaurantinfo['restaurantinfo']=$this->RestoModel>searchRestaurant($searchinfo);

Codeigniter search query combining keywords

I want a search query to return results that match all keywords, but I can only get it to either match any or match string.
I.E. "cake chocolate" either returns all records with "cake" OR "chocolate" in a tag field, or results with the exact tag "cake chocolate", as opposed to what I want, which is to get any record with "cake" AND "chocolate". Here is what I've got:
$key = $this->input->post('searchTerm');
if($key != ''){
// if I comment out the next 10 lines, it becomes MATCH-ANY
$this->db->or_like('product_name',$key);
$this->db->or_like('product_code',$key);
$this->db->or_like('description',$key);
$this->db->or_like('season',$key);
$this->db->or_like('year',$key);
$this->db->or_like('photo_style',$key);
$this->db->or_like('photo_status',$key);
$this->db->or_like('extra_field1',$key);
$this->db->or_like('extra_field2',$key);
$this->db->or_like('additional_notes',$key);
// But if I comment out the next 7 lines instead, I match only the entire string.
$Singlequry = "select * from (select *, concat_ws(' ',product_name,product_code,description,season,year,photo_style,photo_status,extra_field1,extra_field2,additional_notes) merged from records )temp where ";
$keywordsMany = explode(' ',$key);
$tempQuery = array();
foreach($keywordsMany as $each){
$tempQuery[] = " temp.merged like '%".mysql_real_escape_string($each)."%'";
}
$Singlequry = $Singlequry.implode(' or ',$tempQuery); // end of search type comment-out
$makeQuery = true;
}
In case it's not obvious, I really have no idea what I'm doing. I've thrown where_in and other stuff in place of the or_like but with no luck. All this to say, I will need a little hand-holding:)
Unfortunately you cannot produce this query with codeigniter or_like;
Your current code produce your query like this
SELECT * from tablename WhHERE product_name like '%key%' or product_code like '%key%' OR..............
which will return only any match with the key.
BUT I guess you want all match which should be like this
SELECT * from tablename WhHERE product_name like '%key%' AND product_code like '%key%' AND..............
if so you can replace your or_like with where like followings
$this->db->where("product_name LIKE '%$key%'");
$this->db->where("product_code LIKE '%$key%'");
$this->db->where("description LIKE '%$key%'");
It will produce your expected query.It will return results which has all match with key.
You can do it many other way too.
Hope it will will help you.

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Comparing strings returned from a mySql query

I am querying a large number of codes from my database, and need to have some validation before a user can input another code in to the database.
An example code would be this:
TD-BR-010212-xxxxxxxx
Where TD represents a promotion, BR represents a place, the numbers represent a date, and the rest are random.
My problem is that before the code is entered into the DB, I want to check to see if the date and place for that code already exists, as they should not be allwed to enter a code from the same place and date.
I assume it would be something within a loop as I already have:
$location_part_of_td = $code[2].$code[3];
$date_part_of_td = $code[4].$code[5].$code[6].$code[7].$code[8].$code[9];
$trade_day_result = mysql_query('SELECT * from wp_scloyalty WHERE promotion_type = trade-day') or die(mysql_error()); // Pulls all trade day codes from the database and checks the date part of the code.
// the date part exists with the same area part, user cant redeem.
while($info = mysql_fetch_array( $trade_day_result ))
{
$code = $info["product"];
}
But Im just not sure about the best way to check the strings..
You can use a MySQL LIKE clause to get entries in your DB that resemble your code.
Example:
$code_exists = mysql_query(
"SELECT 'a' FROM table_name WHERE column_name LIKE 'TD-BR-010212-%'"
);
if(mysql_num_rows($code_exists) > 0) {
// The specified place/date is taken
} else {
// No promotion at place BR on the specified date.
}
The '%' is used as a wildcard in SQL LIKE clauses.
You have two approach to solving this issue. Assuming you have access to alter the table.
Add a unique constraint to the table base off of the two columns.
Or Your approach by selecting all of the Location and Date, and see if it return any results.
SQL: SELECT COUNT(*) as counter FROM table where column = 'TD-BR-010212-%'
And check to see if counter return > 0;
I would use the LIKE statement in your SELECT and pull entries that start with the same promotion, place, and date. Unfortunately I don't know how your table looks so bear with me:
$promo_query = "SELECT * FROM wp_sclocalty WHERE column_name LIKE 'TD-BR-010212-%'";
$promo_result = mysql_query($promo_query);
if(mysql_num_rows($promo_result) == 0) {
// the promo code has NOT been used
} else {
// the promo code HAS been used
}
try this query
$part_code=substr($code, 0)
$records =mysql_query("select id from tableName where SUBSTRING(code,1,12)= $part_code");
if(mysql_num_rows($records) > 0)
{
// Duplicate exit
}
else
{
// insert code in DB
}
If you can, you'll get better performance and easier coding if you break apart the code into different fields when you save the data in each row. That way you can write queries that specifically check values for the components pieces of the code - you can even set rules in the database (like UNIQUE) to ensure that some parts are kept unique.
Specifically, I'd suggest:
create table your_table (
[... your other columns ...]
promotion char(2),
place char(2),
pr_date date,
pr_ident varchar(50)
)
Your first row would be ([...], 'TD','BR','2012-01-02', 'xxxxxxxx'). And queries would not require unpacking the formatted string - you could say things like "where promotion = 'TD' and place in ('BR','XX') ...". Simple, eh?

Categories