Limit sql result on dbal - php

Im using dbal on Symfony2 to retrieve some info from my table:
$social = $conn->fetchAll('SELECT * FROM page WHERE brand_id = :brand LIMIT :start,:limit', array('brand'=>$brand, 'start'=>(int) $start, 'limit'=>(int) $limit));
Im getting an error only when I add the last part (LIMIT ....), this make me think that i cant limit the result inside the sql query but outside using some kind of command. How can i solve this?
Error:
An exception occurred while executing 'SELECT * FROM page WHERE brand_id = :brand LIMIT :start,:limit' with params {"brand":1,"start":0,"limit":4}:
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 ''0','4'' at line 1

$statement = $connection->prepare(
'SELECT ... LIMIT :limit'
);
$statement->bindValue('limit', $limit, \PDO::PARAM_INT);
$statement->execute();
$result = $statement->fetchAll();

Or you can simply use 3rd argument in the fetchAll($sql, array $params = array(), $types = array()) like that:
$social = $conn->fetchAll('SELECT * FROM page WHERE brand_id = :brand LIMIT :start,:limit', array('brand'=>$brand, 'start'=>(int) $start, 'limit'=>(int) $limit), array(\PDO::PARAM_STR, \PDO::PARAM_INT, \PDO::PARAM_INT));

Related

error in sql where condition on codeigniter

By executing below query i getting this error message
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 'status=1' at line 1 SELECT username,useremail FROM tbl_cart where user_id= 8AND status=1
query
$query = $this->db->query('SELECT username,useremail FROM tbl_cart where
user_id= '.$this->session->userdata('userId').'AND status=1' );
$resultdata['results'] = $query->result_array();
You need to insert an space before AND
$query = $this->db->query('SELECT username,useremail FROM tbl_cart where
user_id= '.$this->session->userdata('userId').' AND status=1' );
^ here
The better way to do it with CI is
$query = $this->db->select('username, useremail')
->where('user_id', $this->session->userdata('userID'))
->where('status',1)
//instead of from CI does get
->get('tbl_cart')->result_array();
result_array() returns the results as an array of arrays while result returns query as an array of objects
if you are using CI it is better to fully take advantage of the query builder classes

Column not found in where clause

I am to php and I am trying to make a page where you can see the public uploads that are stored in a mysql server.
Out of not where the code I have been using starts giving me an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'public' in 'where clause'
I am trying to see how many rows in my db have 'public'
// Find out how many items are in the table
$p = 'public';
$total = $db->query("SELECT COUNT(*) FROM uploads WHERE world_access = $p")->fetchColumn();
I don't know if it is the php or the sql.
// Prepare the paged query
$stmt = $db->prepare('SELECT * FROM uploads WHERE world_access = :y ORDER BY upload_time DESC LIMIT :limit OFFSET :offset');
// Bind the query params
$stmt->bindParam(':y', $p, PDO::PARAM_INT);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
pagination by Simple PHP Pagination script
Enclose $p with quotes
$total = $db->query("SELECT COUNT(*) FROM uploads WHERE world_access = '$p'")->fetchColumn();
Also in your PDO, :y is string right? then use PDO::PARAM_STR

PHP PDO Prepared Statement parameter causing error

I'm having an issue with a prepared statement with a parameter, please see below.
I apologise in advance if this turns out to be some dumb mistake.
The error:
Failed to run query (Project List) - 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 ''0,8'' at line 1
The code:
$limit = ($pagenum - 1) * $page_rows . "," . $page_rows;
print_r($limit); // Prints 0,8 as expected
$query = "SELECT * FROM projects INNER JOIN users ON projects.companyid = users.companyid ORDER BY projects.projectid DESC LIMIT :limit";
$query_params = array (
':limit' => $limit
);
try {
$stmt = $db->prepare($query);
$stmt->execute($query_params);
}
catch (PDOException $ex) {
die("Failed to run query (Project List)" . " - " . $ex->getMessage());
}
What I've tried so far:
Added the SQL Limit as part of the $limit string
Renamed the limit parameter/variables just in case (reserved keyword etc)
Tested the SQL query manually in SQLyog with the LIMIT 0,8 - works fine
Tested the prepared statement by directly passing the limit variable - works fine
Read all similar questions suggested, no similar issues found at least within my level of understanding.
Your $limit parameter is being escaped as one parameter, where it should be escaped as two. Your sql will currently look something like "limit '0, 8';" where it should look like "limit 0, 8";
To solve this, you should split your limit parameter into two. Edit the end of your SQL to look like:
LIMIT :offset, :limit
And your parameter list to look like:
$query_params = array (
':offset' => ($pagenum - 1) * $page_rows,
':limit' => $page_rows
);
As Mr Smith mentioned, you'll also have to add the line:
$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
To ensure the limit parameters are correctly handled as integers rather than strings.

Received "SQLSTATE[42000]: LIMIT ERROR" when using MySQL via PDO

I spent quite a bit of time researching, could not get it resolve. Hence seeking expert advice.
Exact Error:
Error fetching Data: 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 ''LIMIT 0,10''
Here is my SQL :
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
try
{
$sql2 = 'SELECT CASE_JOB_TITLE, STATUS, CASE_WAGE
FROM EMPLOYEE
WHERE LCA_CASE_EMPLOYER_NAME like "%MICROSOFT CORPORATION%"
ORDER BY LCA_CASE_NUMBER ASC :limit';
$sth2 =$pdo->prepare($sql2);
$sth2->bindParam(':limit',$limit );
$result2 = $sth2->execute();
}
Where am I going wrong? If I use the same query in SQL Editor it works fine.
EDIT: Didn't see your first part. Try this:
It should look like:
$limit = ($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
$sql2 = 'SELECT CASE_JOB_TITLE, STATUS, CASE_WAGE
FROM EMPLOYEE
WHERE LCA_CASE_EMPLOYER_NAME like "%MICROSOFT CORPORATION%"
ORDER BY LCA_CASE_NUMBER ASC LIMIT :limit';
I solved it by removing the bind with string. I used the final set of code is ORDER BY LCA_CASE_NUMBER ASC LIMIT :limitFrom,40'; $sth2 =$pdo->prepare($sql2); $sth2->bindParam(':limitFrom –

MySQL Error 1064 Using LIMIT Clause

I'm having a strange issue running a query via PDO prepared statements that I just can't spot the issue. When running the query manually it works just fine. Here is the code (simplified for conciseness):
// Query Parameters
$params = array( 1, 5 );
// Get Products
$query = "SELECT * FROM mydb.Product
WHERE ProductId >= ?
AND IsApproved = 1
AND IsPublic = 1
LIMIT ?";
// Get Database Instance
$dbh = App\App::getDatabase()->getInstance();
// Prepare Query
if( $stmt = $dbh->prepare($query) )
{
if( $stmt->execute($params) )
{
// Return Records
}
}
Removing the LIMIT ? portion from the query returns all results as expected. Instead, when attempting to use the LIMIT and it passes 5 as the value, I get 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 ''5'' at line 5
A dump of the PDOStatement object after preparation shows:
object(PDOStatement)[59]
public 'queryString' => string 'SELECT * FROM mydb.Product
WHERE ProductId >= ?
AND IsApproved = 1
AND IsPublic = 1
LIMIT ?'
I've tried putting a semicolon at the end of the query but that gives same error. Am I having cerebral flatulence and missing something obvious?
TL;DR; Why does my prepared statement fail when using the LIMIT clause with a 1064 error?
I think this could be a duplication of
PDO Mysql Syntax error 1064
The solution is to bind limit parameter forcing it to be an int instead of a string with a simple (int) cast.
just put (int) before your limit value

Categories