1064: You have an error in your SQL syntax near '' - mysql

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 '' at line 4SELECT a.* FROM ws_items a WHERE 1 AND enabled=1 AND visible=1 ORDER BY created DESC LIMIT 0,
I searched the website, but none matches my query. I have no idea on how to use mysql, but I really need to solve this problem...
Maybe someone here knows the solution
if ($params["page_name"]=="index")
{
$filter = "";
if ($_SESSION['user_data']['type']!="admin")
{
$filter = " AND `enabled`=1 AND `visible`=1 ";
}
$sql = "SELECT a.* FROM
`".DB_PREFIX."items` a WHERE 1 $filter
ORDER BY `created` DESC
LIMIT ".($_SESSION['itemsPerPage']*($page-1)).",".$_SESSION['itemsPerPage'];
$items = $DB->getAll($sql);
for($i=0; $i<count($items); $i++)
{
$items[$i][third] = "";
$items[$i][thumb_rating] = rating_bar($items[$i]['id'], '5', 'static');
if($i%3==2)
$items[$i][third] = 'style="margin-right:0;"';
}
$smarty->assign("items", $items);
$sql = "SELECT COUNT(a.id) as `total` FROM
`".DB_PREFIX."items` a WHERE 1 $filter
";
$items = $DB->get($sql);
$total = $items['total'];
$smarty->assign("pagination", $DB->show_pagination($total, $page, $_SESSION['itemsPerPage']));
$output = $this->display(__FILE__, 'latestwallpapers.tpl');
}
return $output;
}

What I think is happening is that
$_SESSION['itemsPerPage']
is null and when multiplying by $page - 1 is being converted to 0 so it's evaluating to 0 in the query, but when concatenated at the end is just producing nothing which is causing the syntax error in the LIMIT clause:
DESC LIMIT 0,

If you have a safe way of creating $filter that prevents SQL injection, then try changing it to:
$sql = "SELECT a.* FROM
`".DB_PREFIX."items` a WHERE 1=1 $filter
ORDER BY `created` DESC
LIMIT ".($_SESSION['itemsPerPage']*($page-1)).",".($_SESSION['itemsPerPage']+0);
If your query ends with LIMIT 0 then it won't return any rows and if it ends LIMIT 0, then it is indeed syntactically incorrect.
You need to make sure that you have a value for the offset.
I have tweaked the query to add zero to the offset, so it should now end with LIMIT 0,0 but beware this won't return any rows. I guess your session variable doesn't have a value.
Why not try var_dump($_SESSION['itemsPerPage']); as suggested by #VMai?
EDIT: I bet you $_SESSION['itemsPerPage'] is set after the first time you reference it. Hence the first time you load the page it fails, then when you refresh, that value is there and it works.

Related

Want to use this but giving error in syntax help me to fix permanent in Query Builder Codeigniter

SELECT installation
FROM `id`
WHERE `outlet_id` = '9'
AND `status` = '1'
GROUP BY `page_rank` `asc`
ORDER BY `page_rank=0`
LIMIT -1, 1
Page Rank=0 gives error
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'asc ORDER BY page_rank=0 LIMIT -1, 1' at line 5
Query using codeigniter query builder class -
$this->db->select('installation') // column name
$this->db->from('id'); // table name
$this->db->where('outlet_id', 9); // condition
$this->db->where('status', 1);
$this->db->group_by('page_rank');
$this->db->order_by('page_rank', 'ASC');
$this->db->limit(1, 0); // will show 1 result starting from 0 ie first result
$query = $this->db->get()->result();
return $query;
Produces
SELECT installation
FROM `id`
WHERE `outlet_id` = 9
AND `status` = 1
GROUP BY `page_rank`
ORDER BY `page_rank` ASC
LIMIT 0, 1
See if it solves your issue.

Compare database timestamp value with today's date and get the result in codeigniter

HI guys i am trying to get the result from db where my table column displaytime is equal to today's date.
So i am trying to check that condition by using where. But i don't know hat is the problem it showing query is wrong
Here is my model:
function getDashboardContent() {
$today = date('Y-m-d H-i');
$this->db->select('cd.details,g.displaytime');
$this->db->where('cd.typeofinfo', 2);
$this->db->where("DATE_FORMAT(g.displaytime,'%Y-%m-%d %H-%i')", $today );
$this->db->from('contentdetails cd');
$this->db->join('content c', 'c.id = cd.contentid');
$this->db->join('group_content gc', 'gc.contentid = c.id');
$this->db->join('groups g', 'g.id = gc.groupid');
$this->db->order_by('cd.id',"DESC");
$this->db->limit('1');
$query = $this->db->get();
print_r($query);
exit;
return $query->result();
}
Here is my 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 ''2018-07-27 12-02' ORDER BY `cd`.`id` DESC LIMIT 1' at line 7
SELECT `cd`.`details`, `g`.`displaytime` FROM `contentdetails` `cd` JOIN `content` `c` ON `c`.`id` = `cd`.`contentid` JOIN `group_content` `gc` ON `gc`.`contentid` = `c`.`id` JOIN `groups` `g` ON `g`.`id` = `gc`.`groupid` WHERE `cd`.`typeofinfo` = 2 AND DATE_FORMAT(g.displaytime,'%Y-%m-%d %H-%i') '2018-07-27 12-02' ORDER BY `cd`.`id` DESC LIMIT 1
Can anyone help me what is the exact problem and what mistake i have done
Thanks in advance.
Why don't you change datetime to timestamp and then compare like this
$this->db->where("TO_SECONDS(g.displaytime)", strtotime($today) );
i have solve my problem by changing this line
$this->db->where("DATE_FORMAT(g.displaytime,'%Y-%m-%d %H-%i')!=", "$today" );
TO
$this->db->where("DATE_FORMAT(g.displaytime,'%Y-%m-%d %H-%i') = '" . $today . "'");

mysql results ordering incorrectly using set FIELD and case

I've got the following variable and query. For some reason, it is sorting the results in the wrong order.
$fieldlist = 'SMOOTH,EMBOSSED,AAR,EMBOSSED AAR';
$strap_query = $db1q->query("
SELECT id,name,tag,size,break,footage,coils_per_skid,core_size,grade,color,cost
FROM Plastic_Strapping
WHERE subcat=$subcat AND visibility='1'
ORDER BY case when tag in ('$fieldlist') then 0 else 1 end, FIELD(tag,'$fieldlist'), sort_order ASC")
or die ('Unable to execute query. '. mysqli_error($db1q));
The order is SUPPOSED TO BE
SMOOTH
EMBOSSED
AAR
EMBOSSED AAR
But instead, it is sorting them in the following INCORRECT order
SMOOTH
AAR
EMBOSSED
EMBOSSED AAR
Any idea why?
is it because EMBOSSED AAR contains EMBOSSED? so its putting it after AAR? If so, any idea how to fix that?
Edit
Placing 'SMOOTH','EMBOSSED','AAR','EMBOSSED AAR' in the ORDER BY FIELD section works; however, I'd still like to be able to edit this via a variable. The following does NOT work.
$fieldlist = "'SMOOTH','EMBOSSED','AAR','EMBOSSED AAR'";
$strap_query = $db1q->query("SELECT id,name,tag,size,break,footage,coils_per_skid,core_size,grade,color,cost FROM Plastic_Strapping WHERE subcat=$subcat AND visibility='1' ORDER BY case when tag in ('$fieldlist') then 0 else 1 end, FIELD(tag, $fieldlist), sort_order ASC") or die ('Unable to execute query. '. mysqli_error($db1q));
throws this error
Unable to execute query. 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 'SMOOTH','EMBOSSED','AAR','EMBOSSED AAR'') then 0
else 1 end, FIELD(tag, 'SMOOTH'' at line 1
Try this:
$fieldlist = 'SMOOTH,EMBOSSED,AAR,EMBOSSED AAR';
$query = "SELECT id,name,tag,size,break,footage,coils_per_skid,core_size,grade,
color,cost FROM Plastic_Strapping WHERE subcat = $subcat AND visibility='1'
ORDER BY FIELD( tag, '".implode("','",explode(',',$fieldlist))."' )";
Update
If your $fieldlist variable is like this:
$fieldlist = "'SMOOTH','EMBOSSED','AAR','EMBOSSED AAR'";
Your query would be like this:
$query = "SELECT id,name,tag,size,break,footage,coils_per_skid,core_size,grade,
color,cost
FROM Plastic_Strapping WHERE subcat = $subcat AND visibility = '1'
ORDER BY case when tag in ($fieldlist) then 0 else 1 end,
FIELD(tag, $fieldlist), sort_order ASC ";

display 10 percent of all items mysql

I'm just a beginner at mysql so in school we got task to do. It goes like this. Display / print 10% of all books from books in falling order. So i tried to use limit, but it doesn't work. What can i do? My code i've tried to use:
select title, price from book
order by price desc
limit (select count(*)*0.1 from book);
thank you for your answers!
limit values have to be hard-coded constants. You can't use variables on them, e.g. select ... limit #somevar is a syntax error. You also can't use sub-queries or other dynamic values either. So you're stuck with either fetching the row count ahead of time and stuff it into the query string as a "hard-coded" value:
$ten_percent = get_from_database('select count(*) / 10 from book');
$sql = "SELECT .... LIMIT $ten_percent";
Or you simply fetch everything and then abort your loop once you've reached 10%:
$sql = "SELECT ....";
$result = mysql_query($sql) or die(mysql_error());
$total_rows = mysql_num_rows($result);
$fetched = 0;
while($row = mysql_fetch_assoc()) {
$fetched++;
if ($fetched >= ($total_rows / 10)) {
break; // abort the loop at 10%
}
... do stuff with $row
}

Selecting all records using SQL LIMIT and OFFSET query

I wonder if there is a way to accomplish:
SELECT * FROM table
by using LIMIT and OFFSET like so:
SELECT * FROM table LIMIT all OFFSET 0
Can I write SQL statement using LIMIT and OFFSET but still getting ALL result?
* of course I can use an IF statement but I rather avoid it if possible
From the MySQL documentation:
To retrieve all rows from a certain offset up to the end of the result
set, you can use some large number for the second parameter. This
statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
So getting all rows might look as follows:
SELECT * FROM tbl LIMIT 0,18446744073709551615;
Yes, it is possible by providing NULL:
SELECT * FROM tab LIMIT NULL OFFSET NULL
db<>fiddle PostgreSQL demo
7.6. LIMIT and OFFSET
LIMIT ALL is the same as omitting the LIMIT clause, as is LIMIT with a NULL argument.
Snowflake LIMIT / FETCH
The values NULL, empty string (''), and $$$$ are also accepted and are treated as “unlimited”; this is useful primarily for connectors and drivers (such as the JDBC driver) if they receive an incomplete parameter list when dynamically binding parameters to a statement.
SELECT * FROM demo1 ORDER BY i LIMIT NULL OFFSET NULL;
SELECT * FROM demo1 ORDER BY i LIMIT '' OFFSET '';
SELECT * FROM demo1 ORDER BY i LIMIT $$$$ OFFSET $$$$;
I used this code in nodeJS with MySQL and it's run well, It's may help you.
Why you use it?
It's reliable because it's a string that will append with query.
If you want to set limit then you can put the limitation with the variable otherwise pass 0 with variable.
var noOfGroupShow=0; //0: all, rest according to number
if (noOfGroupShow == 0) {
noOfGroupShow = '';
}
else {
noOfGroupShow = ' LIMIT 0, '+noOfGroupShow;
}
var sqlGetUser = "SELECT `user_name`,`first_name`,`last_name`,`image`,`latitude`, `longitude`,`phone`,`gender`,`country`,`status_message`,`dob` as user_date_of_birth FROM `tb_user` WHERE `user_id`=?"+noOfGroupShow;
This may not be the best way to do it, but its the first that comes to mind...
SELECT * FROM myTable LIMIT 0,1000000
Replace 1000000 with some adequately large number that you know will always be larger than the total number of records in the table.
As the record will grow up, use mysql_num_rows to dynamically find total amount of records, instead of using some large number.
$cektotalrec=mysql_query("SELECT * FROM TABLE");
$numoffset=mysql_num_rows($cektotalrec);
$numlimit="0";
then:
$final="SELECT * FROM table ".$numlimit.", ".$numoffset"";
Maybe not the cleanest solution but setting limit to a very high number could work. Offset needs to be 0.
Why not use a IF statement where you add the limit and offset to the query as a statement is true?
You might receive an error if you set the limit to a very high number as defined by mysql doc. Thereofre, you should try to limit it 9999999999999, going higher can give you an error unless you set up server to go higher.
You might want to use LIMIT in a function, therefore it is not a bad idea. If you use it in a function, you might want it to be Limit All at one point and limit 1 at another point.
Below, I list an example where you might want your application to have no limit.
function get_navigation($select = "*", $from= "pages", $visible= 1, $subject_id = 2, $order_by = "position", $sort_by = "asc", $offset=0, $limit = 9551615){
global $connection;
$query = " SELECT {$select} ";
$query .= " FROM {$from} ";
$query .= " WHERE visible = {$visible} ";
$query .= " AND subject_id = {$subject_id} ";
$query .= " ORDER BY {$order_by} {$sort_by} ";
$query .= " LIMIT {$offset}, {$limit} ";
mysqli_query($connection, $query);
$navigation_set = mysqli_query($connection, $query);
confirm_query($navigation_set);
return $navigation_set;
}
define ("SELECT", "*");
define ("FROM", "pages");
define ("VISIBLE", 1);
define ("SUBJECT_ID", 3);
define ("ORDER_BY", "position");
define ("SORT_BY", "ASC");
define ("LIMIT", "0");
$navigation_set = get_navigation(SELECT, FROM, VISIBLE, SUBJECT_ID, ORDER_BY, SORT_BY);