SQL Search embeded in PHP for $var depending on search criteria - php

I am trying to gather information from several columns in an SQL DB and feed this into PHP form.
The PHP and embedded SQL query i am running at present is as follows:
< ?php
$region = $_POST['region'];
$serach = "Select clm_england, clm_ireland, clm_scotland, clm_wales
FROM tbl_data
WHEN clm_england LIKE '%$region'
OR clm_ireland LIKE '%$region'
OR clm_scotland LIKE '%$region'
OR clm_wales LIKE '%$region'";
$result = mysql_query($search);
if(!$result) {
echo "Failed:" . mysql_error();
}
? >
I need the query to see clm_england has england in this column and return the result if this is what is searched for. the search form has an option to search for each region or non at all. I am struggling to find a way to return the results based on the region selected to search for or return all results if no region is selected.

You use WHEN and not WHERE in your request :
Select clm_england, clm_ireland, clm_scotland, clm_wales
FROM tbl_data
WHERE clm_england LIKE '%$region'
OR clm_ireland LIKE '%$region'
OR clm_scotland LIKE '%$region'
OR clm_wales LIKE '%$region'

Related

Creating a MYSQL query from results of splitting a string and using LIKE to match keywords in PHP

I am trying to split a string into an array and use these as keywords to make an sql query. I have made a sample of splitting the array and building the sql query. It sort of works but it is giving every table as a result but when I hard copy the built query it comes up with expected results.
This is what I have so far -
The string of keywords split into array and the query is built.
The db is called 'clients_personal' and the table is called 'likes'
$my_search = "paper, glue, discount, bulk";
$new_search = preg_split("/,/", $my_search);
$mmsql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%'";
foreach ($new_search as $value) {
$mmsql = $mmsql." OR likes LIKE '%$value%'";
}
No that results something like :
$mmsql="SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
Now if I search like this, I get all the rows in the db?
$sql = "$mmsql";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id=$row["id"];
echo $id;
}
}
But if I query is as hard coded it gives predicted results?
$sql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
$result = $conn->query($sql);
I have a feeling its to do with quotes and i have tried removing them but no good? Any advice?
Also I an using this type of search as I found it on here.
The problem is here $new_search = preg_split("/,/", $my_search); use $new_search = preg_split("/, /", $my_search); instead.
The items in the string are separated by a comma and a space (", ") so you should split the string with that.

Where clause in PHP MySQL not working with Like keyword

I have been trying to filter my data according to the c_type = "Engineering' and search keyword in the search box. The searching part is working fine but the query is not working it displays the whole result.
This is for filtering my result
$query1 = mysqli_query($conn, "SELECT * FROM col_details WHERE c_type = 'Engineering' and c_name LIKE '%{$name}%' OR location LIKE '%{$name}%' ");
I am trying to display all the results in my col_details table with c_type is Engineering and c_name or location is taken from the Search Box.
The search box code is working fine but it's displaying all data and not the data with c_type = 'Engineering'.
Any help appreciated.
Thanks.
Your OR clause should be wrapped in brackets,
Try this:
$query1 = mysqli_query($conn, "SELECT * FROM col_details WHERE c_type = 'Engineering' and (c_name LIKE '%{$name}%' OR location LIKE '%{$name}%') ");
Hope it helps.

What is the best query for php-mysql search?

I have a search engine which is pretty straight forward. The query is below.
$sql = "SELECT * FROM events WHERE eventname LIKE '%".$_POST["search"]."%'
OR place LIKE '%".$_POST["search"]."%'
OR country LIKE '%".$_POST["search"]."%'
OR date LIKE '%".$_POST["search"]."%'
LIMIT 40";
But, Problem with this is this,
if I put the 'eventname' in search-box it is okay and it saws data from eventname column correctly. Or if I search only for place or country or date individually, it shows data correctly. But, if I search (FOR EXAMPLE) for both eventname and place together search results shows nothing. Using this query what are the changes I have to make to get it working?
Additionally I want to say that I have seen some of the query like "MATCH ... AGAINST". Though I don't want to use that, but if there are no other way what could be that "MATCH...AGAINST" query for this?
Here is my full code. They are straight forward. And I am working on a weird client's project and he want it to be like this and security is not a fact for him. So, you might notice some security issue which will be solved later. but the query first.
<?php
include_once("admin/connection/db.php");
$output = '';
$sql = "SELECT * FROM events WHERE eventname LIKE '%".$_POST["search"]."%'
OR place LIKE '%".$_POST["search"]."%'
OR country LIKE '%".$_POST["search"]."%'
OR date LIKE '%".$_POST["search"]."%'
OR date AND country LIKE '%".$_POST["search"]."%'
OR date AND place LIKE '%".$_POST["search"]."%'
OR date AND eventname LIKE '%".$_POST["search"]."%'
LIMIT 40";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$output .= "<a class='search-result' href='".$row["link_pdf"]."'><li><i class='fa fa-trophy'> </i> ".$row["eventname"].'<br/>'.date('Y-m-d', strtotime($row["date"])).' || '.$row["place"].', '.$row["country"].'<img src="logos/'.$row["country"].'.png" width="30px" height="18px;" /></li></a>';
}
echo $output;
}else {
echo "<li>No Data Found Macthing Your Query</li>";
}
?>
Here is the link where you can check it directly
http://speed-timing2.6te.net/
I believe your search query term is for example "event_name place_name" and in this case your query will not work. You can use FULLTEXT search instead.
For example
at first set fulltext index for eventname, place, country field as those are string fields.
$sql = "SELECT * FROM (
SELECT *, MATCH (eventname, place, country) AGAINST ('".$_POST["search"]."' IN BOOLEAN MODE) AS score
FROM events
ORDER BY score DESC
) AS temp
WHERE temp.score>0 OR temp.date LIKE '%".$_POST["search"]."%'
";
Please check manual here http://dev.mysql.com/doc/refman/5.7/en/fulltext-boolean.html

php / mysql pagination - count from multiple fields

I'm trying to follow this pagination tutorial http://www.phpfreaks.com/tutorial/basic-pagination to add pagination to my search page i've built. The following line from the tutorial:
$sql = "SELECT COUNT(*) FROM numbers";
I need it to count based on rows which match user inputted data that's being pulled in from a small form. This is the working query i was running before trying to add pagination
$raw_results = mysql_query("SELECT * FROM Pictures WHERE (`RimWidth` LIKE '%".$RimWidth."%') AND (`TyreWidth` LIKE '%".$TyreWidth."%') AND (`Aspect` LIKE '%".$Aspect."%') AND (`TyreDia` LIKE '%".$TyreDia."%') AND (`TyreMan` LIKE '%".$TyreMan."%')") or die(mysql_error());
I'm unsure how i can add this. I've tried this:
$sql = mysql_query("SELECT COUNT FROM Pictures WHERE (`RimWidth` LIKE '%".$RimWidth."%') AND (`TyreWidth` LIKE '%".$TyreWidth."%') AND (`Aspect` LIKE '%".$Aspect."%') AND (`TyreDia` LIKE '%".$TyreDia."%') AND (`TyreMan` LIKE '%".$TyreMan."%')") or die(mysql_error());
But it just errors out.
How do i need to format the query?
You are getting an error using COUNT instead of COUNT(expression), so you have to change your query so that you use SELECT COUNT(*) as in the first example you gave.
EDIT That's how you can get the exact count:
$query = "SELECT COUNT(*) FROM Pictures WHERE (`RimWidth` LIKE '%".$RimWidth."%') AND (`TyreWidth` LIKE '%".$TyreWidth."%') AND (`Aspect` LIKE '%".$Aspect."%') AND (`TyreDia` LIKE '%".$TyreDia."%') AND (`TyreMan` LIKE '%".$TyreMan."%')";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_fetch_row($result);
COUNT(*) - skipped what to count.
Basically if your query is working but you need to get the count instead of actual data you should be good with replacing the columns you're trying to select with the COUNT(*)
One more thing. The result of your last code line is not the string itself. It's the resource that can be used to fetch the count you need.

Search suggestion box inputs space in front of search query

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!

Categories