I have a mysql query which simply looks into mysql to find LIKE strings and displays the result.
Within the same mysql query, I have 2 LIKE.
1 is always a single string and the other one can be single and sometimes multiple strings separated by commas.
when I use my code, I get no results at all even though I have all the fields in the mysql database and I also have all the search strings in the columns.
This is my code:
$area = 'London';
$res = 'santandar, HSBC, RBS, ';
$sql = "SELECT * FROM banks WHERE location LIKE '%$area%' AND name LIKE '%$res'";
I also tried it with preg_match and it didn't return anything:
$sql = "SELECT * FROM banks WHERE location LIKE '%$area%' AND name LIKE '".preg_match($res)."'";
If I remove the second LIKE and my code looks like below, it works just fine:
sql = "SELECT * FROM banks WHERE location LIKE '%$area%'";
So the issue starts when I try to search using a comma separated string.
Could someone please advise on this issue?
EDIT:
The PHP varibles are POSTS so they can be anything in each post.
they are like so:
$area = $_POST['area'];
$res = $_POST['res'];
you should use an OR condition:
$res_array = explode(',' $res)
$num_elem= count($res_array) // with this value you can build dinamically the query
"SELECT * FROM banks WHERE location LIKE '%$area%'
AND ( name LIKE concat('%', $res_array[0]),
OR LIKE concat('%', $res_array[1])
OR LIKE concat('%', $res_array[2]) ";
You are going to need to blow this out into separate LIKEs with an OR, such as:
...WHERE location LIKE '%{$area}' AND (name LIKE '%{$name1}%' OR name LIKE '%{$name2}' OR ...)
You could write this fairly simply with some PHP logic:
function build_like_or( $values, $field_name ) {
// Create an array from the comma-separated values
$names = explode( ',', $values );
// Trim all the elements to remove whitespaces
$names = array_map( 'trim', $names );
// Remove empty elements
$names = array_filter( $names );
$where = array();
// Loop over each, placing the "LIKE" clause into an array
foreach( (array)$names AS $name ) {
$where[] = "{$field_name} LIKE '%{$name}%'";
}
// Glue up the LIKE clauses.
$where = '(' . implode(' OR ', $where) . ')';
// Results will be something like:
// $where = "(name LIKE '%santadar%' OR name LIKE '%HSBC%')"
return $where;
}
Usage:
$area = 'London';
$res = 'santandar, HSBC, RBS, ';
$name_where = build_like_or( $res, 'name');
$sql = "SELECT * FROM banks WHERE location LIKE '%$area%' AND {$name_where}";
// echo $sql outputs "SELECT * FROM banks WHERE location LIKE 'London' AND (name LIKE '%santadar%' OR name LIKE '%HSBC%' OR name LIKE '%RBS%')
Related
Using single Chinese characters in my search.
分坨坨 is my example here. The last two (坨坨) are completely the same - duplicates, if you will.
My first variable is $where which looks like this:
$where = array();
foreach ( $qtwo as $word ) {
$where[] = "CHS LIKE '%" . $word . "%'";
}
$where = implode(' OR ', $where);
Which prints:
CHS LIKE '%分%' OR CHS LIKE '%坨%' OR CHS LIKE '%坨%'
(The following is not really consequential but helps to explain my variables:)
I get them into an array called $where3 - which prints like this:
ORDER BY CASE CHS
WHEN '分' THEN 1
WHEN '坨' THEN 2
WHEN '坨' THEN 3
My query looks like this:
{$results4 = $db->query("SELECT * FROM FOUR WHERE $where $where3
END;");
while ($row4 = $results4->fetchArray()) {
So they print in the order that they came in - and all duplicates are represented in both variables.
When I run the query though - only the first of the duplicates gets printed back (坨).
How can I get it to print both of the duplicates?
I would like to ask about an issue i'm facing.
I have the full name in 1 column stored, example: "John Doe".
But on perform a search for example:
SELECT * FROM client WHERE name LIKE '%Doe John%';
Result: 0 Rows.
If i switch to the exact match store in database it found a row.
SELECT * FROM client WHERE name LIKE '%John Doe%';
Result: 1 Row.
My question is, how to do to search in database without taking the order of word.
In OOP framework the code is:
$like = 'Doe John';
$this->db->select('*')->from('client')->like('name', $like)->get();
Also i tested this but i got the same result:
$this->db->select('*')->from('client');
if($this->containTwoWords($like)) {
$explode = explode(' ', $like);
foreach($explode as $exploded){
$this->db->like('name', $exploded);
}
} else {
$this->db->like('name', $like);
}
$this->db->get();
function containTwoWords($like){
if(strpos($like, ' ') !== false) {
return true;
}
return false;
}
If somebody passed trough this and has better solution i appreciate the sharing !.
One option for your example case would be to check for the first and last names separately:
SELECT * FROM client WHERE name LIKE '%Doe%' AND name LIKE '%John%'
If you have exhausted such tricks with the LIKE operator, then you can look into using MySQL's full text search capabilities.
Try something like this:
<?php
$search_term = 'john doe abc';
$keywords = explode(" ", preg_replace("/\s+/", " ", $search_term));
foreach($keywords as $keyword){
$wherelike[] = " name LIKE '%$keyword%' ";
}
$where = implode(" and ", $wherelike);
$query = "select * from client where $where";
echo $query;
//select * from client where name LIKE '%john%' and name LIKE '%doe%' and name LIKE '%abc%'
?>
Try this name like '%John%' and name like '%Doe%'
If you are wanting to explode the $like variable into first/last name (and you always expect 2 names, separated by a space), then this should work for you.
PHP has the built-in explode() method which does exactly what you are asking.
$like = "John Doe";
$name = explode(" ", $like);
// This created a 0-based array, meaning the first item as split
// by the space between John and Doe is given the array index of 0.
// $name[0] = John
// $name[1] = Doe
So in practice with MySQL that could be used as the following:
$query = "SELECT * FROM client WHERE name LIKE '%" . $name[0] . "%' AND name LIKE '%" . $name[1] . "%'";
For more information on the explode() function, check out the PHP manual at: http://php.net/manual/en/function.explode.php
Hope this helps!
I am trying to figure out how and what function i need for my query, still not sure on using Like, concat or what part etc.
My situation is as such
1.) I have multiple columns(Country, City, State, Location)
2.) Only 1 search input
3.) Search input can be 1 word, or multiple words also ignore spacing(e.g. "Center City or CenterCity or Center City Philadelphia) etc
And it will return the rows that matches the words from the different columns.
Below is my attempt, but it is not returning anything at the moment. Thanks for your time
Php:
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
include 'connect.php';
if($_POST)
{
$searchaddress = ($_POST['searchaddress']);
$result=mysqli_query($con,"SELECT *
FROM Listing WHERE CONCAT(country,state,city,Location) LIKE '%$searchaddress%' AND Status='Open'") or die( mysqli_error($con));
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
}
?>
Without knowing your exact data and what $searchaddress is like, it is hard to tell why it fails.
You are talking about ingoring whitespaces, but just pass in a single searchtag - and the expression LIKE '%something something else%' will not ignore whitespaces.
If you want to have the least amount of results with all given words matching, you should put in more effort and use a or/and combination of searchtags / columns. You can do this programmatically.
Assuming, you have 2 keywords entered: Center Detroid, you basically want to generate the searchquery:
FROM Listing WHERE
(
country LIKE '%Center%' OR
state LIKE '%Center%' OR
city LIKE '%Center%' OR
Location LIKE '%Center%'
)
AND
(
country LIKE '%Detroid%' OR
state LIKE '%Detroid%' OR
city LIKE '%Detroid%' OR
Location LIKE '%Detroid%'
)
To achieve that, you need to know two things:
The fieldnames you want to search in.
The keywords.
Then, the following snippet will generate the where part as required:
$search = "Detroid City Center";
$keywords = explode (" ", $search);
$columns = array("country", "state", "city", "location");
$andParts = array();
foreach ($keywords AS $keyword){
$orParts = array();
foreach($columns AS $column){
$orParts[] = $column . " LIKE '%" . mysql_real_escape_string($keyword) . "%'";
}
$andParts[]= "(" . implode($orParts, " OR ") . ")";
}
$and = implode ($andParts, " AND ");
echo $and;
The example given in the array would produce
(
country LIKE '%Center%' OR
state LIKE '%Center%' OR
city LIKE '%Center%' OR
location LIKE '%Center%'
)
AND
(
country LIKE '%City%' OR
state LIKE '%City%' OR
city LIKE '%City%' OR
location LIKE '%City%'
)
AND
(
country LIKE '%Detroid%' OR
state LIKE '%Detroid%' OR
city LIKE '%Detroid%' OR
location LIKE '%Detroid%'
)
This will Match ANY row, where Center, City or Detroid is appearing AT LEAST ONCE in ONE of all (search-)fields per row.
Updated answer for searching each word in the address fields:
$searchaddress = "some address to find";
$address_parts = explode(" ", trim($searchaddress));
$sql_parts = array();
foreach($address_parts as $part) {
$sql_parts[] = 'full_address LIKE "%'.$part.'%"';
}
$query = 'SELECT *, CONCAT(country,state,city,Location) AS full_address FROM Listing WHERE `Status` = "Open" HAVING '.implode(' OR ', $sql_parts);
I have a user query and a database. My database contains tables. What I am curious to know, is my method for querying the database. What I'm thinking is:
Separate the query into an array split by a space
Loop through each word and do a LIKE '%{$word}%' OR
Above that, just prior to each iteration, do an 'AND'
The problem is, its not working correctly. Its not dicing done to precise emails that match my queries. Here is my code:
$i=0;
$userQuery = $_POST['q']; // q = "Jonathan gmail"
$sql = "SELECT * FROM addresses WHERE ";
$parts = explode(' ',$userQuery);
$cnt=count($parts);
foreach($parts as $part){
$part = mysql_real_escape_string($part);
if($i!==$cnt-1){
$sql.="(
addresses.name LIKE '%".$part."%' OR
addresses.localpart LIKE '%".$part."%' OR
addresses.domain LIKE '%".$part."%'
) AND
";
} else {
$sql.="(
addresses.name LIKE '%".$part."%' OR
addresses.localpart LIKE '%".$part."%' OR
addresses.domain LIKE '%".$part."%'
)
";
}
$i++;
}
}
My question is whats wrong with this logic? It seems accurate.
First of all: This will break on a single word.
Second: This is everything else but safe from an SQL attack.
Now - how I'd do it
$parts = preg_split('/[\s,]+/',$userQuery);
$sql=array();
foreach($parts as $part) {
$part=mysql_real_escape_string($part); //Or whatever works with your DB access framework
$sql[]="(addresses.name LIKE '%$part%' OR addresses.localpart LIKE '%$part%' OR addresses.domain LIKE '%$part%')";
}
$sql=implode(' AND ', $sql);
$sql="SELECT * FROM addresses WHERE $sql";
hey something like this:
foreach($parts as $key => $part){
$part=mysql_real_escape_string($part);
$sql .= sprintf("(
addresses.name LIKE %s OR
addresses.localpart LIKE %s OR
addresses.domain LIKE %s
)", $part);
if ($key!=($cnt-1)) {
$sql .= " AND ";
}
}
Little notice, you're using $i variable before initializing it. Also maybe it will be a better way to use REGEXP. Something like:
// $search_terms = '%Jonathan%|%gmail%'
$sql = "addresses.name REGEXP $search_terms OR addresses.localpart REGEXP $search_terms OR addresses.domain REGEXP $search_terms";
More details on REGEXP
i have a variable and an user_name i want to search on a string(function_description) of the user_name for it
whats wrong with this :
$function_keywords = mysql_real_escape_string($_POST['function_keywords']);
if($function_keywords=="" || empty($function_keywords)){
redirect("show.php?functions=PHP");
}
//trim whitespace from the stored variable
$trimmed = trim($function_keywords);
//separate key-phrases into keywords
$trimmed_keywords = explode(" ",$trimmed);
// Build SQL Query for each keyword entered
foreach ($trimmed_keywords as $trimm){
// MySQL "MATCH" is used for full-text searching.
//this code is ebv weird , should check out soon!
$query = "SELECT *
FROM functions
WHERE isEnabled=1 AND isPrivate=0
AND function_description LIKE '{$trimm}'
AND user_name='{$user_name}'
";
// Execute the query to get number of rows that contain search kewords
$results=mysql_query ($query,$connection);
as far as "like" syntax goes you have to use the '%' symbol. if you query for
select * from table where column like '%yourkeyword%'
then it returns any rows with 'yourkeyword' inside the table column.
your statement will be true only if the column = 'yourkeyword'
That's highly inefficient. If someone puts in 5 keywords, you'd be running the search 5 times and getting 5 sets of results. Try something more along these lines:
$words = $_POST['function_keywords'];
if ($words == '') {
... abort ...
}
$parts = trim(explode(' ', $words));
$clauses = array();
foreach($parts as $part) {
$clauses[] = "function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause = implode(' OR ' , $clauses);
$sql = "SELECT .... WHERE (isEnabled=1) AND (isPrivate=1) AND (user_name='$user_name') AND ($clause)";
$result = mysql_query($sql) or die(mysql_error());
This'll build up a long series of or statements for each keyword specified, and run the whole thing as a single query.
To see if the function_description contains the keyword you need to use '%' which stands for anything much the way '*' does in unix. Try function_description LIKE '%{$trimm}%'