MySQL error 1064 when performing an SELECT query - php

I have code like this:
function search_keyword(){
$keyword = trim($_POST['keyword']);
$search_explode = explode(" ", $keyword);
$x = 0;
$sql = " ( SELECT name, id_global_info AS id, body AS body, tag AS tag ,info_type_id AS info_type, \"global_info\" AS mytable FROM global_info WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) UNION ALL ";
$sql .= " ( SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, \"person\" AS mytable FROM person WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) UNION ALL ";
$sql .= "( SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, \"event\" AS mytable FROM event WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) UNION ALL ";
$sql .= "( SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, \"caffe\" AS mytable FROM caffe WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) ";
echo $sql;
$q = $this->db->query($sql);
return $q = $q->num_rows() == 0 ? FALSE : $q->result();
}
When I search for exapmle
"mali oglasi"
I get following error:
Error Number: 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 'AND name LIKE '%mali%' AND name LIKE '%oglas%' ) UNION ALL (
SELECT name, id_e' at line 1
This is MySQL query it is producing:
( SELECT name, id_global_info AS id, body AS body, tag AS tag ,info_type_id AS info_type, "global_info" AS mytable FROM global_info WHERE name LIKE '%mali%' AND name LIKE '%oglas%' )
UNION ALL
( SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, "person" AS mytable FROM person WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%' )
UNION ALL
( SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, "event" AS mytable FROM event WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%' )
UNION ALL
( SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, "caffe" AS mytable FROM caffe WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%' )
What seems to be an error?

First thing's first: don't forget to escape your input value. This can be done in your case either on the initial value, or for each iteration of the foreach loop on $each
// If your query() method calls mysql_query()
$keyword = mysql_real_eascape_string(trim($_POST['keyword']));
// Or if query() is mysqli::query()
$keyword = $this->db->real_escape_string(trim($_POST['keyword']));
// Or if this is Codeigniter's API
$keyword = $this->db->escape_like_str(trim($_POST['keyword']));
You need to reset $x at the start of each foreach loop:
// Reset $x to 0 before the start of each of your loops.
$x = 0;
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
Note: It is generally advisable to use parameterized queries instead of building the query by concatenation and interpolation. Codeigniter uses ? placeholders for that.

Your query errors reside in the second, third and fourth SELECT statements, as you have WHERE AND name rather than WHERE name

Related

PHP filters combining into one SQL query

I'm trying to filter through my database according to filters done by visitors.
$query = "select * from Sheet1 where";
//filter query start
if (!empty($brand)) {
$branddata = implode("','", $brand);
//testing removing query
$query .= " Brand in('$branddata') and";
}
if (!empty($model)) {
$modeldata = implode("','", $model);
//testing removing query
$query .= " Model in('$modeldata') and";
}
/* if(!empty($model) && empty($brand)){
} */
if (!empty($spower) && !empty($epower)) {
$query .= " Power>='$spower' and Power<='$epower' and";
}
if (!empty($sprice) && !empty($eprice)) {
$query .= " Doors>='$sprice' and Doors<='$eprice'";
}
$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));
The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.
Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.
Append $query .= " 1 = 1"; at the end. I did some modification in your given code. Have a look.
<?php
$query = "SELECT * FROM `Sheet1` WHERE";
//filter query start
if(!empty($brand)){
$branddata = implode("','",$brand);
$query .= " (Brand in('$branddata')) AND";
}
if(!empty($model)){
$modeldata = implode("','",$model);
$query .= " (Model in('$modeldata')) AND";
}
if(!empty($spower) && !empty($epower)){
$query .= " (Power>='$spower' AND Power<='$epower') AND";
}
if(!empty($sprice) && !empty($eprice)){
$query .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}
$query .= " 1 = 1"; //Added new line
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>
Add AND on each query appended in if conditions. Then, at last add $query .= " 1 = 1";. Which will save you from extra AND coming at the end. If none of the conditions satisfy, then your query will be SELECT * FROM Sheet1 WHERE 1 = 1. Simple. And, don't forget to differentiate between conditions in query. Differentiate your conditions like how I did by opening and closing brackets.
I would do it this way
$filters=array();
if(!empty($brand)){
$branddata =implode("','",$brand);
//testing removing query
$filters[]= " Brand in('$branddata')";
}
if(!empty($model)){
$modeldata =implode("','",$model);
//testing removing query
$filters[]= " Model in('$modeldata') and";
}
if(!empty($spower) && !empty($epower)){
$filters[]= " Power>='$spower' and Power<='$epower' and";
}
if(!empty($sprice) && !empty($eprice)){
$filters[]= " Doors>='$sprice' and Doors<='$eprice'";
}
$query = "select * from Sheet1 where";
foreach ($filters as $filter) {
$query.=' AND '.$filter;
}
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));

Inner join in server side data table with php

//define index of column
$columns = array(
0 =>'id',
1 =>'employee_name',
2 => 'employee_salary',
3 => 'employee_age'
4 =>'employee_City',
5 => 'employee_State',
6 => 'employee_Pin'
);
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['search']['value']."%' ";
$where .=" OR employee_salary LIKE '".$params['search']['value']."%' ";
$where .=" OR employee_age LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
Help me please, I have 3 tables, all tables has a primary key as table_id how to get data from 3 tables using server side datatables how to implement join query in this code. Here employee_City, employee_State and employee_Pin are stored in second table. Employ personal details Stored in third table. How to join all tables?
I have just take dummy name of table city , state , pincode ..
Try with this query :
$sql = "SELECT id, employee_name, employee_salary, employee_age, employee_City, employee_State, employee_Pin FROM employee LEFT JOIN city ON employee.cityID = city.id LEFT JOIN state ON employee.stateID = state.id LEFT JOIN pincode ON employee.pincodeid = pincode.id ";
if( !empty($params['search']['value']) ) {
$sql .=" WHERE ";
$sql .=" ( employee_name LIKE '%".$params['search']['value']."%' ";
$sql .=" OR employee_salary LIKE '%".$params['search']['value']."%' ";
$sql .=" OR employee_age LIKE '%".$params['search']['value']."%' )";
}
$sql.=" ORDER BY employee_name";
These links will help you make join query:
https://www.sitepoint.com/understanding-sql-joins-mysql-database/
http://www.techonthenet.com/mysql/joins.php

How to reduce Mysql execution Time?

I'm using Mysql 5.5.16. I've a query where i combine 3 queries using union opeartor... Each query contains more than 10000 records.
My Query looks like...
$search_qry1 = " (SELECT PC_name as name FROM profile_category_tbl WHERE PC_status=1 and PC_parentid!=0 and (";
$search_qry2 = " (SELECT PROFKEY_name as name FROM profile_keywords_tbl WHERE PROFKEY_status=1 and (";
$search_qry3 = " (SELECT COM_name as name FROM ".$C."_company_profile_tbl WHERE COM_status=1 and (";
$order_by = "ORDER BY";
$word_length = explode(" ", $my_data);
for($i=0; $i <= count($word_length) - 1; $i++) {
$dt = $word_length[$i];
if ($dt) {
if ($i == 0) {
$or="";
}
else {
$or="OR";
}
$search_qry1 .= " $or regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(PC_name)) LIKE '%$dt%' ";
$search_qry2 .= " $or regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(PROFKEY_name)) LIKE '%$dt%' ";
$search_qry3 .= " $or regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(COM_name)) LIKE '%$dt%' ";
$order_by .= " IF(name LIKE '%$dt%',1,0) ";
}
if ($i == count($word_length) - 1) {
$search_qry1 .= ")";
$search_qry2 .= ")";
$search_qry3 .= ")";
}
if ($i != count($word_length) - 1) {
$order_by .= "+ ";
}
}
$search_qry1 .= " GROUP BY PC_name )";
$search_qry2 .= " GROUP BY PROFKEY_name )";
$search_qry3 .= " GROUP BY COM_name )";
$search_qry = "select name from ( $search_qry1 UNION ALL $search_qry2 UNION ALL $search_qry3 )a $order_by desc LIMIT 0,25";
It works perfectly... but it takes the time to execute it - more than 4 secs... for each search.... how possible to reduce its execution time?.... If anyone know an idea about this please let me know....
Actually I run this query for auto-complete search. If type "Rest" in search box, then
The Output Should be,
Family Restaurants
Everest Park
Fast Food Restaurants
Everest Park Residency
Fish Restaurant
Everest Power Solution
Fish Restaurants
Thanks in Advance,
Jeni
You are using regex_replace and like "%foobar%",
that actually slows down your query significat, since mySql has to do a fulltext search and the regex operation on every single row. Maybe it's faster if you do these operations after you fetched your results, using php instead of mysql.
The main problem is that you're doing a full scan of each table to check the like '%$dt%' condition. No matter which indices you have on the table, none of them will be used.
But if you post the final SQL sentence and what are you trying to do maybe we could help.

mysql_fetch_array not working for 1 row query result

My query works fine. but wen trying get unique value from the table mysql fetch array not work.
this is my sql
A-2815 is the item code of the vehicle. this field is unique. Expecting result is item_code A-2815 's vehicle details.
$sql = "SELECT vehicle.id, item_code, make, model, vehicle_type, color, showroom_id, ";
$sql .= "adding_user_Id, approved, image_1 ";
$sql .= "FROM images, vehicle ";
$sql .= "WHERE vehicle.id=images.item_id ";
$sql .= "AND (item_code LIKE '%A-2815%' ";
$sql .= "OR make LIKE '%A-2815%' ";
$sql .= "OR model LIKE '%A-2815%' ";
$sql .= "OR vehicle_type LIKE '%A-2815%' ";
$sql .= "OR color LIKE '%A-2815%' ";
$sql .= "OR showroom_id LIKE '%A-2815%') ";
$sql .= "AND activate=1 ";
$sql .= "AND type_of_image=1 ";
this is my php code.
<?php
$query = mysql_query($sql);
while($result = mysql_fetch_array($query)){
echo $result['item_code'];
echo $result['make'];
echo $result['model'];
echo $result['vehicle_type'];
echo $result['color'];
echo $result['showroom_id'];
}
?>
this working ok when results are more then 1 row. but problem is when result is 1 row then it is not working.
while ($result = mysql_fetch_array($query, MYSQL_ASSOC)) {
// assoc
echo $result['item_code'];
}
MySQLi solution for this
$connect = mysqli_connect('localhost', 'root', 'pwd', 'dbname');
$sql = "select * from sometable";
$query = mysqli_query($connect, $sql);
while ($result = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
// assoc
echo $result['item_code'];
}

Php Syntax Help

I'm working on a search function, it was working fine four days ago, now it's returning 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 'AND state = 'AZ '' at line 1
what is the proper syntax for this line?
if($search_state !== "") {
$query .="AND state = '" . $search_state . " ' " ;
the entire portion is:
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new WHERE dummy = '' ORDER BY state ASC ";
if($search_co !== "") {
$query .= "AND name LIKE '%" . $search_co ."%' ";
}
if($search_first !== "") {
$query .= "AND contact LIKE '%" .$search_first."%' ";
}
if($search_last !== "") {
$query .= "AND contact LIKE '%" .$search_last."%' ";
}
if($search_city !== "") {
$query .="AND city = ' " . $search_city . " ' ";
}
if($search_state !== "") {
$query .="AND state = '" . $search_state . " ' " ;
}
You can't put AND conjunctions for your WHERE clause after an ORDER BY. Your ORDER BY clause has to come after the entirety of the WHERE clause.
You need to put the AND statements after the where, and before the sort_by.
Move the sort_by to the end of the php (append to the query string), and it should work.
Try this:
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new WHERE dummy = '' ";
if($search_co !== "") {
$query .= "AND name LIKE '%".$search_co."%' ";
}
if($search_first !== "") {
$query .= "AND contact LIKE '%".$search_first."%' ";
}
if($search_last !== "") {
$query .= "AND contact LIKE '%".$search_last."%' ";
}
if($search_city !== "") {
$query .= "AND city = '".$search_city."' ";
}
if($search_state !== "") {
$query .= "AND state = '". $search_state."' " ;
}
$query.= "ORDER BY state ASC"
As was said by others, your order by statement has to come last. Also, you had spaces surrounding the city name in the city = portion of the query. While this is valid SQL syntax, it's only going to return results where the city name is surrounded by spaces. I'm guessing that's not what you wanted.
Also, you may want to add some more fields to your order by. Right now, it will order by state, but will records come back randomly by state. Maybe something like
$query.= "ORDER BY state, city, name, id"
Finally, just FYI, if you're not carefully sanitizing your search inputs, this approach is susceptible to SQL Injection.
Also, you seem to have spaces between the single and double quotes which will make the query like this: AND state = ' AZ ' which is probably not what you want. You can also avoid the additional quotes and concatenations in PHP by using this syntax:
$query .= " AND state = '$search_state' ";
Of course I have to mention that you should sanitize your inputs to protect against SQL injection.
The WHERE part comes before the AND's in your code, which is wrong. This is what you want
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new WHERE dummy = '' ";
if($search_co !== "") {
$query .= "AND name LIKE '%" . $search_co ."%' ";
}
...
$query .= " ORDER BY state ASC ";
Also, for completeness sake, you could make the code a bit easier to read:
$query .= "AND name LIKE '%$search_co%' ";
because your string is double quoted
I think this might work:
$query = "SELECT id, name, contact, contact2, address1, address2, city, state, postalcode, country, location, workphone, fax, email, webaddress, region, rail, food, forest, metal, bulk, chem, general, paper FROM companies_new ";
$conditions = array();
if(!empty($search_co)) {
$conditions[] = "name LIKE '%" . $search_co ."%' ";
}
if(!empty($search_first)) {
$conditions[] = "contact LIKE '%" .$search_first."%' ";
}
if(!empty($search_last)) {
$conditions[] = "contact LIKE '%" .$search_last."%' ";
}
if(!empty($search_city)) {
$conditions[] = "city = '" . $search_city . "' ";
}
if(!empty($search_state)) {
$conditions[] = "state = '" . $search_state . "' " ;
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
}
$query .= " ORDER BY state ASC";
Edit: The original version used empty, it should have been !empty. It's fixed now.
Edit 2: This also assumes you've already sanitized the variables using mysql_real_escape_string or similar.
Note that ORDER BY has to be after the WHERE clauses.
implode takes an array and turns it into a string with the specified string between the elements. So, given:
$myArray = array('A', 'B', 'C');
you can do
$myString = implode(' and ', $myArray);
which would put "A and B and C" into $myString.

Categories