Syntax combining partial query into one - php

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

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 to perform a multi sql search via php in one field

i am using this sql search to find a title and artist in my database. I have on field containing infos like "ref.1570 title artist.mp4". When I do the search it works but in one direction only, i would like to get the result whatever the order i do the search... to be more precise if i search "title artist" no problem i found it. If i search "artist title" no way ... how can you help me making php sql search both directions ?
Best regards and thank you for your help.
Phil
i am using this code :
if ($search != null) {
$sql = 'SELECT * FROM `catalog` WHERE (`file`LIKE "%' . $search . '%")';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE (`file`LIKE "%' . $search . '%")';
}
Why don't you split keyword $search with space and append with Like statement in the query. Eg:
if ($search != null) {
$keywords=explode(" ",$search);
$sql = 'SELECT * FROM `catalog` WHERE 1=1'; // just to append OR condition.This won't affect anything as the condition will always be true.
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE 1=1 ';
foreach($keywords as $key){
if(!empty($key)){
$sql.=' And file Like \'%'.$key.'\%';
$sqlCount.=' And file Like \'%'.$key.'\%';
}
}
}
I believe this will work as you expected.
I think you won't get around a foreach:
if ($search != null) {
$arrayOfSearchTerms = explode(' ', $search);
$sql = 'SELECT * FROM `catalog` WHERE ';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE ';
$termNumber = 0;
foreach ($arrayOfSearchTerms as $term) {
$addingSql = '';
if ($termNumber > 0) {
$addingSql = ' OR ';
}
$addingSql .= '(`file` LIKE "%') . $term . '%")';
$sql .= $addingSql;
$sqlCount = $addingSql;
$termNumber++;
}
}
You need to iterate over your search terms and add this terms into your 'LIKE'-Statement
you can try this research: it does a LIKE %word% for every word. If you want more powerfull research you should use tools like elasticsearch etc...
This way you could do:
$parts = explode(" ",$search)
$queryParts = array();
foreach ($parts as $part) {
$queryParts[] = `artist`LIKE "%' . $part . '%" ;
}
// this way we can have like %artist% AND like %title%
$querySearch= implode(" AND ", $queryParts);
$sql = 'SELECT * FROM `catalog` WHERE (". $querySearch .")';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE (`". $querySearch .")';
you have solved my problem i know now hos to correctly explode a request into variables ..
$search = $name;
$explode=explode(" ",$search);
print_r (explode(" ",$explode));
and then i use my sql request like this
$sql = 'SELECT * FROM `catalog` WHERE (`idc` LIKE "%' . $search . '%" OR `file` LIKE "%' . $search . '%" OR `title` LIKE "%' . $explode[0] . '%" AND `artist`LIKE "%' . $explode[1] . '% " OR `artist`LIKE "%' . $explode[0] . '%" AND `title`LIKE "%' . $explode[1] . '%")';
and it is working !
COOL
Use the multi query functions,
in mysqli should be : mysqli_multi_query();
More info on : Mysqli Multiquery

MySQL syntax error in string built by PHP

I have some code which generates a MySQL query string called $query:
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
$clue = $_POST['postcode'];
$onwhat="Postcode";
$query .= $onwhat . " like '%$clue%') order by id desc";
$result = mysql_query($query, $connection) or die(mysql_error());
This returns something like:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which works fine. I've then altered the code because I want to search on more fields so it now reads:
$remap = array("Postcode", "Street", "HouseNum", "District", "Town");
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
for ($i=0; $i<=4; $i++) {
if ($_POST[strtolower($remap[$i])]!="") {
$clue = $_POST[strtolower($remap[$i])];
$query .= $remap[$i] . " like '%$clue%') order by id desc";
break;
}
}
This also returns:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which on the face of it is identical but it generates this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'like '%dn%' order by id desc' at line 1
In both cases $query contains the same "text" but for some reason isn't treated as a valid MySQL query in the updated code, can anyone tell me why?
One possible problem could be the interpretation of the content here.
If you use:
$query .= $remap[$i] . " like '%$clue%') order by id desc";
All that is inside "" gets to be interpreted. Thus there could be unwanted side effects that you don't see at first glance and can explain what is happening. To avoid this it would have to be changed to:
$query .= $remap[$i] . ' like ' . "'" . '%' . $clue . '%' . "') order by id desc";
Even though more clunky in terms of how big it is, it makes sure that $lue and also the % are not interpreted as all in between ' ' is not interpreted.
See if this help you solve your problem?
$remap = array(
"Postcode",
"Street",
"HouseNum",
"District",
"Town"
);
for ($i = 0; $i <= 4; $i++)
{
if ($_POST[strtolower($remap[$i]) ] != "")
{
$query = "select * from Surveys where surveylayoutid='12' and customerid='1' and (";
$clue = $_POST[strtolower($remap[$i]) ];
$query.= $remap[$i] . " like '%$clue%') order by id desc";
$query_done[] = $query;
unset($query);
$result = mysql_query($query_done[$i], $connection) or die(mysql_error());
// Display your result here
}
}
I tried changing your code abit, and it seems the result is something like this
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%Postcode%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Street like '%Street%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (HouseNum like '%HouseNum%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (District like '%District%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Town like '%Town%') order by id desc

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

How to check an array in a sql query?

So I need to check an array in my query:
$query = "SELECT * FROM post WHERE ".$select." LIKE '%".$search."%' AND ID NOT IN '" .$Lastvar."'";
$Lastvar is my array. I have no idea where to go from here an any help would be appreciated.
EDIT: Here's my full query:
$Lastvar = array();
mysql_select_db('submisions', $dbconn);
$query = "SELECT * FROM post WHERE ".$select." LIKE '%".$search."%' AND ID NOT IN (" . join(", ", $Lastvar) . ")";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo 'No results were found';
exit;
}
If the ID is of integer type:
$query = "SELECT * FROM post WHERE ".$select." LIKE '%".$search."%'
AND ID NOT IN (" . join(", ", $Lastvar) . ")";
Do it like this:
$query = "SELECT * FROM post WHERE ".$select." LIKE '%".$search."%' AND ID NOT IN ('" .join("', '", $Lastvar).")";

Categories