How to add more options to the LIKE query - php

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%') ";

Related

mysql dynamic queries without clause where

In the following example there is a base query. Other parameters can be dynamically added to complete the query.
However, my base query has no clause WHERE.
What is the best way to deal with it.
If I use in the base query, for example, WHERE 1 = 1, it seems to solve, but I have some doubts that is a correct solution.
$myQuery = "SELECT fr.oranges, fr.aplles, fr.bananas,
FROM fruits fr
LEFT JOIN countrys ct ON fr.id_fruit = ct.id_fruit";
if(!empty($countrys){
$myQuery .= " AND countrys = ? ";
}
if(!empty($sellers){
$myQuery .= " AND seller = ? ";
}
$myQuery .=" GROUP BY fr.id_fruit ORDER BY fr.fruit ASC";
Edited: I fixed a writing gap from $empty to empty.
The WHERE 1=1 is a simplistic hack that works well because it simplifies your code. There is a great post here which explains the performance implications of WHERE 1=1. The general consensus is it will have no effect on performance.
Also, slight note ($empty) is probably not a function you've defined. I think you want empty(). You could write it like this:
$myQuery = "SELECT fr.oranges, fr.aplles, fr.bananas,
FROM fruits fr
LEFT JOIN countrys ct ON fr.id_fruit = ct.id_fruit";
$where = [];
if(!empty($countrys){
$where[] = "countrys = ?";
}
if(!empty($sellers){
$where[] = "seller = ?";
}
if (!empty($where)) {
$myQuery .= " WHERE " . implode(" AND ", $where);
}
$myQuery .= " GROUP BY fr.id_fruit ORDER BY fr.fruit ASC";
You can use an array to control your SQL like this:
$where = [];
if(!$empty($countrys){
$where[] = " countrys = ? ";
}
if(!$empty($sellers){
$where[] = " seller = ? ";
}
if(count($where) > 0) {
$myQuery .= " WHERE ".implode('AND', $where);
}

php mysql order by relevance

$fields = array('surname', 'firstname', 'maiden', 'birth', 'death', 'obittext'); $conditions = array();
foreach($fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`$field` LIKE '%" . $_POST[$field] . "%'";
}
}
$sql = "SELECT * FROM obits ";
if(count($conditions) > 0) {
$sql .= "WHERE " . implode (' AND ', $conditions);
}
$result = mysqli_query($con, $sql);
So far this allows me to search either one or more than one field like a surname and/or a date of birth. What I would like to do is also sort this by relevance as it currently sorts by the primary ID (ex: I want smith to come before klingensmith if I search smith).
I am really new at this, getting this far required much gnashing of teeth so please explain like I'm 5. I already tried:
$result = mysqli_query($con, $sql, ' ORDER BY relevance DESC ');
which just broke it. I suspect I need to add another condition but I don't know what or where. Very much thanks, and much respect to all you people who understand this stuff.

How to use like in an in sql statement

Hi I'm using PHP to try and retrieve data from a database while looping through an array inside the in statement like this.
$sql2 = "SELECT * FROM pixacour_pixacourt.UserCaseMessages WHERE FavorIDs IN (" ;
$count = 0;
foreach($followingArray as $value)
{
if($count==count($followingArray)-1)
{
$sql2 .= "LIKE";
$sql2 .= "%'".$value."'%";
}
else
{
$sql2 .= "LIKE";
$sql2 .= "%'".$value."'%,";
}
++$count;
}
$sql2 .= ")";
I get this error, that says
"trying to get property of non object"
I can't figure out what is going on any suggestions would be much appreciated thank you for your time.
You should not be using LIKE in an IN clause but you do need to comma delimit elements. No need to keep track of the count, either. foreach will cease when the array has been traversed and you can trim off the trailing comma.
$sql2 = "SELECT * FROM pixacour_pixacourt.UserCaseMessages WHERE FavorIDs IN (" ;
foreach($followingArray as $value)
{
$sql2 .= "'".$value."', ";
}
$sql2 = rtrim($sql2,',');
$sql2 .= ");";
If this fails, like Gordon says, echo $sql2 and the syntax error will probably be clear.
If you do indeed need to use LIKE and wildcard matching, you could append multiple OR clauses, one for each $value.
$sql2 = "SELECT * FROM pixacour_pixacourt.UserCaseMessages WHERE " ;
$whereClause = "";
foreach($followingArray as $value)
{
$whereClause .= " OR FavorIDs LIKE '%".$value."%' ";
}
$whereClause = ltrim($whereClause, " OR");
$sql2 .= $whereClause . ";";
UPDATE 1/9/15
I realized there's a bug in this code in that when $followingArray is empty, we'd receive a MySQL syntax error because the query ends with "WHERE". Here's a new version which resolves that bug:
$sql2 = "SELECT * FROM pixacour_pixacourt.UserCaseMessages" ;
if(count($followingArray) >= 1) {
$sql2 .= " WHERE";
}
$whereClause = "";
foreach($followingArray as $value)
{
$whereClause .= " OR FavorIDs LIKE '%".$value."%' ";
}
$whereClause = ltrim($whereClause, " OR");
$sql2 .= $whereClause . ";";

Multiple textbox for search results

Hello I have a page with multiple textboxes, each textbox should search with its own query. Im using the following php code for this:
php
if ($val != null){
$where = " WHERE boekingsnummer LIKE '".$val."%'";
}
How can I get it to work with the other textboxes ?
Any help is much appreciated.
You could do something like this:
$where = " WHERE 1 = 1 ";
$where .= "AND boekingsnummer LIKE '".$val."%' ";
$where .= "AND ?? LIKE '".$val2."%' ";
Use like this
$sql_add= '';
if ($val1 != '')
{
$sql_add = " AND boekingsnummer LIKE '".$val1."%'";
}
if ($val2 != '')
{
$sql_add .= " AND field2 = '".$val2."%'";
}
and so on....
$sql = "SELECT * FROM TABLE_NAME WHERE 1=1 $sql_add";
may this will help you

php mysql search from 2 columns

$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%'";

Categories