php mysql search from 2 columns - php

$where = "";
$keywords =preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword) {
$where .= "`title` LIKE '%$keyword%'";
if ($key != ($total_keywords - 1)) {
$where .= " AND ";
}
}
$results = "SELECT `id`, `username`, `title`, LEFT(`description`, 90) as `description`, `file`, `code`, `type`, `size`, `date` FROM `files` WHERE $where ORDER BY id DESC LIMIT $start, $per_page";
$where .= "`title` LIKE '%$keyword%'"; // this case I am searching only in column `title` I want to search too in column `type` with sign '.' I don't know how to include '.' in search result for `type`
Example search for file.exe and get all results with this condition file.exe. Or somebode search only .exe get all results with type .exe
$where .= "title, type LIKE '%$keyword%'";//I did it like this no result
$where .= "title AND type LIKE '%$keyword%'";//I did it like this no result
$where .= "title LIKE '%$keyword%' AND type LIKE '%$keyword%'";//I did it like this no result
Someone knows how I can get it my results with title type with sign '.'???

$where .= "`title` LIKE '%$keyword%' OR type LIKE '$type'";
Updated Code
$pos = strpos($keyword, '.');
if($pos > 0) {
$parts = explode('.', $keyword);
$type = array_pop($parts);
$file = array_pop($parts);
$where .= "`title` LIKE '%$file%' AND type LIKE '%$type%'";
}
else {
$where .= "`title` LIKE '%$keyword%' OR type LIKE '%$type%'";
}

$where .= "`title` LIKE '%$keyword%' OR type LIKE '%$type%'";

Related

Search returning no results in "reverse" order

I have a database filled with addresses. 6 columns (id, Name, Address, City, State, Zip, dt)
My code is run with ajax for live search. Currently I can mostly find what I'm looking for with my queries. The problem I'm running into is this. If I search for "90210 Steve Jones" I get no results but if I search for "Steve Jones 90210" it finds the row(s).
Here is my code:
$query = "SELECT * FROM db";
if($_POST['query'] != '')
{
$postq = mysql_real_escape_string($_POST['query']);
$query .= "WHERE CONCAT(Name,Address,City,State,Zip) LIKE '%".str_replace(' ', '%', $postq)."%'";
}
$query .= 'ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
$statement->execute();
Any help would be appreciated
One of the solutions is to split the search string by spaces and then do a multiple like comparison operations
So the code is:
<?php
if($_POST['query'] != '') {
$postq = mysql_real_escape_string($_POST['query']);
$pieces = explode(" ", $postq);
$index=0;
$substring="";
while ($index < count($pieces)) {
$substring .=" CONCAT(Name,Address,City,State,Zip) like '%" . $pieces[$index] . "%'" ;
if ($index !=count($pieces)-1){
$substring .= " and ";
}
$index++;
}
$query = "SELECT * FROM db where ";
$query .= $substring;
$query .= ' ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
$statement->execute();
}
?>
You could break up your query by spaces and test for each.
$query = "SELECT * FROM db";
$where = [];
$values = [];
$ss = [];
if($_POST['query'] != '')
{
foreach( explode(' ', $_POST['query']) as $p) {
$postq = mysql_real_escape_string($p);
$where[]= "(CONCAT(Name,Address,City,State,Zip) LIKE ? )";
$values[] = "%$postq%";
$ss[]='s';
}
$query .= " WHERE " . implode(" OR ", $where);
}
$query .= ' ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
if(count($values)>0) $statement->bind_param(implode('',$ss), ...$values);
$statement->execute();

How do you ignore dashes and commas in a php search bar

Currently, in my search bar, I'm able to find the name of a city if I type it in exactly the way it has been put into the database. For example: Nuits-Saint-Georges or Durham, NC.
I would like for my users to be able to type in Nuits Saint Georges or Durham NC.
The Cities are located in "location".
function Wo_GetAllJobs($filter_data = array()) {
global $wo, $sqlConnect;
$data = array();
$query_one = " SELECT * FROM " . T_JOB . " WHERE status = '1'";
if (!empty($filter_data['c_id'])) {
$category = $filter_data['c_id'];
$query_one .= " AND `category` = '{$category}'";
}
if (!empty($filter_data['after_id'])) {
if (is_numeric($filter_data['after_id'])) {
$after_id = Wo_Secure($filter_data['after_id']);
$query_one .= " AND `id` < '{$after_id}' AND `id` <> $after_id";
}
}
if (!empty($filter_data['keyword'])) {
$keyword = Wo_Secure($filter_data['keyword']);
$query_one .= " AND (`title` LIKE '%{$keyword}%' OR `location` LIKE
'%{$keyword}%') ";
}
if (!empty($filter_data['user_id'])) {
$user_id = Wo_Secure($filter_data['user_id']);
$query_one .= " AND `user_id` = '{$user_id}'";
}
if (!empty($filter_data['type'])) {
$type = Wo_Secure($filter_data['type']);
$query_one .= " AND `job_type` = '{$type}'";
}
if (!empty($filter_data['length'])) {
$user_lat = $wo['user']['lat'];
$user_lng = $wo['user']['lng'];
$unit = 6371;
$query_one = " AND status = '1'";
$distance = Wo_Secure($filter_data['length']);
if (!empty($filter_data['c_id'])) {
$category = $filter_data['c_id'];
$query_one .= " AND `category` = '{$category}'";
}
if (!empty($filter_data['after_id'])) {
if (is_numeric($filter_data['after_id'])) {
$after_id = Wo_Secure($filter_data['after_id']);
$query_one .= " AND `id` < '{$after_id}' AND `id` <> $after_id";
}
}
if (!empty($filter_data['keyword'])) {
$keyword = Wo_Secure($filter_data['keyword']);
$query_one .= " AND (`title` LIKE '%{$keyword}%' OR `location` LIKE
'%{$keyword}%') ";
}
if (!empty($filter_data['user_id'])) {
$user_id = Wo_Secure($filter_data['user_id']);
$query_one .= " AND `user_id` = '{$user_id}'";
}
if (!empty($filter_data['type'])) {
$type = Wo_Secure($filter_data['type']);
$query_one .= " AND `job_type` = '{$type}'";
}
Split your keyword by spaces then implode them by %
//TODO query_one
//$query_one .= " AND (`title` LIKE ? OR `location` LIKE ?) ";
$stmt = $mysqli->prepare($query_one);
$keyWord = "%" . implode("%", explode(" ", $keyword)) . "%";
$stmt->bind_param("s", $keyWord));
$stmt->bind_param("s", $keyWord));
$stmt->execute();
Remember that prepared statements is a MUST and easy to switch to
note:
using % at the beginning of the keyword will make the optimizer not be able to use the index on that column, if any exists, so if your data size is big and you started to encounter performance issues, you can go to Full Text Search (FTS) check this
Don't worry about case sensitivity comparisons on MySQL
And Regarding the case of the comparison that MySQL will perform, I will quote from the manual "Case Sensitivity in String Searches"
For nonbinary strings (CHAR, VARCHAR, TEXT), string searches use the
collation of the comparison operands. For binary strings (BINARY,
VARBINARY, BLOB), comparisons use the numeric values of the bytes in
the operands; this means that for alphabetic characters, comparisons
will be case-sensitive.
..
The default character set and collation are utf8mb4 and utf8mb4_0900_ai_ci, so nonbinary string comparisons are case insensitive by default.
This is how I ended up solving this issue.
if (!empty($filter_data['keyword'])) {
$keyword = $filter_data['keyword'];
$keywordSearch = Wo_Secure(str_replace(',','',str_replace('-','',str_replace('.','',str_replace(' ', "", $keyword)))));
$keyword = Wo_Secure($keyword);
$query_one .= " AND (`title` LIKE '%{$keyword}%' OR REPLACE(REPLACE(REPLACE(REPLACE(`location`,' ',''),'-',''),'.',''),',','')LIKE '%{$keywordSearch}%') ";
}

Syntax combining partial query into one

I would like to create a new query based on another.
Example:
$query = "SELECT * FROM `table2` WHERE `field2` > 0 AND (`field3` LIKE '%".$keyword%."%' OR `field4` LIKE '%".$keyword."%' ** insert new parameters from another query here ** ) AND `field5` <= 0\"';
I tried below and didn't work. Wonder if I am getting it right.
$keyword = $_POST['keyword'];
$query = "SELECT * FROM `table1` WHERE `field` LIKE '%$keyword%'";
if ($result = $con->query($query)) {
$new_query = '\"SELECT * FROM `table2` WHERE `field2` > 0 AND (`field3` LIKE \'%\".$keyword%.\"%\' OR `field4` LIKE \'%\".$keyword.\"%\'';
while ($row = mysqli_fetch_assoc($result)) {
$keyword2 = $row['something'];
$new_query .= " OR `field2` LIKE '%" . $keyword2 . "%' OR `field4 LIKE '%" . $keyword2 . "%'";
}
$new_query .= ') AND `field5` <= 0\"';
}
if ($result = $con->query($new_query)){
.........etc
}
Appreciate if someone can help!!
Try this
$new_query = "SELECT * FROM table2 WHERE field2 > 0 AND (field3 LIKE '%$keyword%' OR field4 LIKE '%$keyword%' ";
...
$new_query .= " OR `field2` LIKE '%$keyword2%' OR `field4 LIKE '%$keyword2%'";
...
$new_query .= ') AND `field5` <= 0';
var_dump($new_query); // have a look at the query you have created

How to add more options to the LIKE query

Sorry about the confusing title, I am newbie and have no idea what to call my problem.
I am building (well..trying) to create a business listing website and I found this search script, which gets results from table. So, I pasted this, tried it and it works, but only searches one field at a time, I can't search two fields at the same time. only data from field: "company_name" is retuned. But, I need to make this flexible and append it to search from field name 'categories' so, I in short I need PHP to search two rows i.e.
'company_name' & 'categories' field.
Here is the script, for which I don't know how to add the additional syntax for.
$keywords = preg_split('/[\s]+/',$keywords);
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword) {
$where .= "`company_name` LIKE '%$keyword%' ";
if($key != ($total_keywords - 1)) {
$where .= " AND ";
}
the problem is in here: $where .= "company_nameLIKE '%$keyword%' ";
if you need to see the whole script here it is.
function search_clients($keywords){
$returned_results = array();
$where = "";
$keywords = preg_split('/[\s]+/',$keywords);
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword) {
$where .= "`company_name` LIKE '%$keyword%' ";
if($key != ($total_keywords - 1)) {
$where .= " AND ";
}
}
$results = "SELECT `company_name`, LEFT(`company_details`,150)
as `company_details`, `category` FROM `clients`
WHERE $where";
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0 ;
if($results_num === 0) {
return false;
} else {
while($results_row = mysql_fetch_assoc($results)) {
$returned_results[] = array(
'company_name' => $results_row['company_name'],
'company_details' => $results_row['company_details'],
);
}
return $returned_results;
}
}
Was this written in PHP? What type of Database are you connecting too? These bits of information would be helpful! Sometimes different databases can be picky about how thier queries are structured!
Never the less, try this code and see if it creates the desired results:
foreach($keywords as $key=>$keyword) {
$where .= "( `company_name` LIKE '%$keyword%' "
. " OR `categories` LIKE '%$keyword%' )";
if($key != ($total_keywords - 1)) {
$where .= " AND ";
}
}
you can use an OR in this case with parentheses like that
$where .= "(`company_name` LIKE '%$keyword%' OR `category` LIKE '%$keyword%') ";

Building MySQL searching query using LIKE in PHP

I make a PHP MySQL search, the custom may be type something like word or word1 word2 or word1 word2 word3... I need to get the final query like
$qry = "SELECT title,content,date
FROM articles WHERE
(title like '%$word1%' and title '%$word2%')
OR
(content like '%$word1%' and content title '%$word2%')"
OR
(title like '%$word1%' and content title '%$word2%')
OR
(title like '%$word2%' and content title '%$word1%'); // make sure custom type words all match in database column title and content, maybe only '%$word1%', or maybe multi words '%$word1%', '%$word2%', '%$word3%'...
I use some code below, but it could not reach my request. how to make it right? Thanks.
$qry = "SELECT title,content,date FROM articles";
if($_REQUEST['search']!=""){
$searchText = $_REQUEST['search'];
$words = preg_split("/\s+/",$searchText);
$uniqueWords = array_keys(array_flip($words));
$parts = '';
foreach($uniqueWords as $word){
$parts[] = " content like '%$word%' ";
}
$where = implode(" AND ", $parts);
foreach($uniqueWords as $word){
$parts[] = " title like '%$word%' ";
}
$where1 = implode(" AND ", $parts);
foreach($uniqueWords as $word){
$parts[] = " title like '%$word%' OR content like '%$word%' ";
}
$where2 = implode(" AND ", $parts);
$qry .=" WHERE $where OR $where1 OR $where2 Order By date DESC ";
}
I'm not sure exactly what you're after (are you wanting to match any keyword in title or contents or match both keywords to both columns...?) But what about something like this:
$keywords = explode(' ',mysql_real_escape_string($_REQUEST['search']));
$qry = "SELECT title,content,date FROM articles WHERE (";
$qry2 = '';
foreach($keywords as $n => $word)
{
$qry2 .= " title LIKE '%$word%' OR content LIKE '%$word%' OR";
}
$qry .= trim($qry2, 'OR');
$qry .= ") ORDER BY title";
Not tested this, but it seems ok.

Categories