SELECT * FROM `orders` WHERE id LIKE %1%
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 '%1%' at line 1
PHP
$sql = "SELECT * FROM `orders` ";
switch ($_POST['criteria']) {
case 'id':
$sql .= "WHERE id LIKE %" . (int) $_POST['search_input'] . "%";
break;
case 'OCR':
$sql .= "WHERE OCR LIKE %" . $db->quote($_POST['search_input']) . "%";
break;
case 'name':
$arr = explode(' ', $_POST['search_input']);
$firstname = $arr[0];
if (isset($arr[1])) {
$lastname = $arr[1];
} else {
$lastname = null;
}
$sql .= "WHERE firstname LIKE %" . $db->quote($firstname) . "% AND lastname LIKE %" . $db->quote($lastname) . "%";
break;
}
echo $sql;
$stmt = $db->query($sql);
$rows = $stmt->fetchAll();
The query is being outputted and it looks fine to me, but for some reason I am getting a syntax error ( I assume it is), however I can't seem to spot any problems?
LIKE operator is a string function. So you need to enclose it with single quotes(').
SELECT * FROM `orders` WHERE id LIKE '%1%';
You have quotes missing around your strings, so your quesries look something like:
SELECT * FROM orders where id LIKE %55%
instead of:
SELECT * FROM orders where id LIKE '%55%'
$sql = "SELECT * FROM `orders` ";
switch ($_POST['criteria']) {
case 'id':
$sql .= "WHERE id LIKE '%" . (int) $_POST['search_input'] . "%'";
break;
case 'OCR':
$sql .= "WHERE OCR LIKE '%" . $db->quote($_POST['search_input']) . "%'";
break;
case 'name':
$arr = explode(' ', $_POST['search_input']);
$firstname = $arr[0];
if (isset($arr[1])) {
$lastname = $arr[1];
} else {
$lastname = null;
}
$sql .= "WHERE firstname LIKE '%" . $db->quote($firstname) . "% AND lastname LIKE '%" . $db->quote($lastname) . "%'";
break;
}
echo $sql;
$stmt = $db->query($sql);
$rows = $stmt->fetchAll();
This answer should fix your problem but I strongly suggest you use = instead of LIKE since you are looking for unique orders identified by id.
Yhe way you script is currently written, if id is 55, you will get orders 55, 255, 5500, 1559...
Kindly write pattern in single qoute '' and like me sure
incorrect SELECT * FROM `orders` WHERE id LIKE %1%
correct- SELECT * FROM `orders` WHERE id LIKE '%1%'
Related
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
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
so I am building a search script and meed to pass on two variables, but first I want to make sure that the SQL QUery is correct so I am hard-coding the variable for now. So my variable is
$comma_separated = "'Alberta','Ontario'";
This is getting passed through to the query, which looks like this:
$sql = "SELECT * FROM persons WHERE 1=1";
if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
if ($province)
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' WHERE province IN ($comma_separated)";
$sql .= " ORDER BY surname";
and then when the query runs, I get this message:
cannot run the query because: 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 'WHERE province IN ('Alberta','Ontario') ORDER BY surname LIMIT 0, 5' at line 1
But to me the query looks right, what am I missing here?
Thanks in advance.
You can't have WHERE in there twice. You also seem to be trying to filter on province values in two different ways. Based on the assumption that $province will always be an array of values (even if only a single value is given), you can try this:
$sql = "SELECT * FROM persons WHERE 1=1";
if (!empty($firstname)) {
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
}
if (!empty($surname)) {
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
}
if (!empty($province)) {
array_walk($province, function($value, $key_not_used) use ($mysqli) {
return mysqli_real_escape_string($mysqli, $value);
});
$sql .= " AND province IN ('" . implode(',', $province) . "')";
}
$sql .= " ORDER BY surname";
Your SQL contains two WHERE's.
SELECT * FROM persons WHERE 1=1
AND firstname='fn'
AND surname='sn'
AND province='p'
WHERE province IN ($comma_separated)
ORDER BY surname
Change the last bit to:
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' AND province IN ($comma_separated)";
Which becomes:
AND province='p'
AND province IN ('Alberta','Ontario')
Change the last part to:
if ($province)
$sql .= " AND province IN (" . mysqli_real_escape_string($mysqli,$comma_separated) . ")";
//$type has value of "Hello+World"
$type = $_POST['series'];
$sql = "select max(id) from TABLE_NAME where type = " . $type;
$result = sybase_query ($sql, $db_ro_conn) or die(db_error("query failed $sql"));
$row = sybase_fetch_row($result)
I get the error "incorrect syntax near "=". y15, procedure N/A in the $sql line.
What are the possible reasons why this is happening? Somehow it doesn't work. Would appreciate any help, thanks!
Put quotes around your $type like this:
$type = $_POST['series'];
$sql = "select max(id) from TABLE_NAME where type = '" . $type. "'";
$result = sybase_query ($sql, $db_ro_conn) or die(db_error("query failed $sql"));
$row = sybase_fetch_row($result)
Let me start with this. ALWAYS escape POST/GET values in your query!
The error is probably caused by $type is string and not quoted. Try changing $sql to
$sql = "select max(id) from TABLE_NAME where type = '" . $type."'";
You are not quoting the value:
$type = str_replace("'", "''", $_POST['series']);
$sql = "select max(id) from TABLE_NAME where type = '" . $type . "'";
This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"