pdo pagination limit error - php

I have a pagination script and I am trying to change the mysql database into pdo database but I get this error; 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 'DESCLIMIT -2,2' at line 1
The part of code what gives me troubles is;
$limit = "LIMIT ".($page-1)*$perPage.",$perPage";
//$offset = ($page - 1) * $perPage;
$query = $db->prepare('SELECT image_id FROM images WHERE album_id= ? ORDER BY image_id DESC'.$limit);
$query->bindValue(1, $album_id);
//$query->bindParam(':limit', $limit, PDO::PARAM_INT);
try{
$query->execute();
}catch (PDOException $e){
die($e->getMessage());
}
I searched on google for solutions but my pdo knowledge is not good enough to use it right. I got errors like; SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens, because of $query->bindParam(':limit', $limit, PDO::PARAM_INT);
I don't know how to solve this, can anybody help me?
Thanks...

It seems mysql don't like negative offsets. You can make it this way
$limit = ($page-1)*$perPage;
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sql = 'SELECT image_id FROM images WHERE album_id=? ORDER BY image_id DESC LIMIT ?,?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$album_id,$limit,$perPage]);
$ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

In the tutorial the first query was $count_query = $db->prepare('SELECT NULL FROM images where album_id= ?');
That worked in the tutorial but not here, I think that gave the negative value.
I changed this into $count_query = $db->prepare('SELECT * FROM images where album_id= ?');
and the error is gone. Other errors is showing up now, hopefully I can solve that.
Thanks for helping me solve this error.

Related

My PDO Prepared Statement is not working with a fetchALL and Limit [duplicate]

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 2 years ago.
I am trying to get some products from my database with a prepared PDO statements. The formula worked well if I included the variable inside the SQL but of course this is really bad practice.
Working formula:
protected function getSomeProducts($somequantity){
$sql = "SELECT * FROM products ORDER by ID DESC LIMIT $somequantity";
$stmt = $this->connect()->query($sql);
$result = $stmt->fetchAll();
return $result;
My approach to the prepared statement:
protected function getSomeProducts($somequantity){
$sql = "SELECT * FROM products ORDER by ID DESC LIMIT ?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$somequantity]);
$result = $stmt->fetchAll();
return $result;
}
This is the error message I get:
Fatal error
: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''6'' at line 1.
Any idea what Im doing wrong could be?
replace the below line
$stmt->execute([$somequantity]);
with
$stmt->bindParam(1, $somequantity, PDO::PARAM_INT);
$stmt->execute();

PHP PDO doesn't bind correctly [duplicate]

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 7 years ago.
$conn = getConn();
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select * from posts where fk_user_id in (select id_user_1 from contacts where id_user_2=:_id) or (select id_user_2 from contacts where id_user_1=:_id) or :_id order by date desc limit 15 offset :_offset";
$stmt = $conn->prepare($sql);
$stmt->bindParam('_id', $id);
$o = "0";
$stmt->bindParam('_offset', $o);
Connection failed: 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'' at line 1
For some reason it doesn't bind the param correctly; if I manually put a 0 in the SQL everything works.
Fix: I fixed if by adding PDO::PARAM_INT. $stmt->bindParam(':_offset', $offset, PDO::PARAM_INT);
You're binding parameters incorrectly. It should be:
$stmt->bindParam(':_id', $id);
$offset = 0;
$stmt->bindParam(':_offset', $offset, PDO::PARAM_INT);

PDO SQLSTATE[42000] on simple select query

Im just new with programming in OOP, so im writing a function but it gives an error, i think im using PDO wrong, actually i now it for sure, but i dont now how to fix it. This is my code im using currently:
public function takedrugs($soort, $hoeveelheid, $id){
$conn = $this->conn;
$drugsophalen = $conn->prepare('SELECT * FROM gebruikers WHERE id=:id');
$drugsophalen->execute(array(':id' => $id));
$result = $drugsophalen->fetch();
$huidigdrugs = $result[$soort];
if($huidigdrugs >= $hoeveelheid){
//Voldoende drugs dus drugs afnemen
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET :soort = :soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->execute(array(
':soort' => $soort,
':hoeveelheid' => $hoeveelheid,
':id' => $id));
} else {
return false;
}
}
So when i use this function i get an error, its all about the SET :soort = :soort - :hoeveelheid.
This is the error i get:
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 ''Cannabis' =
'Cannabis' - '2000', WHERE id ' at line 2' in
I hope there are some people who now how to fix it since i dont :S
Thanks in advance!
You CANT bind column names SEE Complex Cases in PDO info.
Also as Jason states about lazy binding use bindParam OR bindValue
TRY
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET $soort = $soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->bindParam(':hoeveelheid', $hoeveelheid, PDO::PARAM_INT);
$drugsafnemen->bindParam(':id', $id, PDO::PARAM_INT);
$drugsafnemen->execute();
You have two problems:
First, by using execute() all your values are being treated as a string. This results in the syntax error:
UPDATE gebruikers SET field = 'Cannabis' - '2000' ...
I assume this is not your intention. Instead, use bindParam() so you can define these parameters as integers.
$drugsafnemen->bindParam(':soort', $soort, PDO::PARAM_INT);
Second, you should are setting the column name dynamically (:soort). As such, it too is getting interpolated with $soort, which is probably not your intention.

PDO error message 1064

I am having trouble getting this to work I will include the code both working and what I am trying to accomplish. In the first code it is non-working and gives me an error message: Connection failed: 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 ':userName ANDpassword=:userPass' at line 1
I have tried several different combinations of syntax and still no luck. In the second code example it is working code and basically I am trying to get rid of all the unnecessary code to just obtain a $row count from the function to verify that there was 1 row that matched the query.
function checkLogin($conn,$myusername, $mypassword) {
$stmt = $conn->prepare('SELECT COUNT(*) FROM `CLL_users` WHERE `user_name`= :userName AND `password`= :userPass');
$stmt->bindValue(':userName', $myusername);
$stmt->bindValue(':userPass', $mypassword);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
}
function checkLogin($conn,$myusername, $mypassword) {
$stmt = $conn->prepare('SELECT COUNT(*) FROM `CLL_users` WHERE `user_name`= :userName AND `password`= :userPass');
$stmt->bindValue(':userName', $myusername);
$stmt->bindValue(':userPass', $mypassword);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
}

How to add variable values inside pdo->query

I want to upgrade my current code which is constantly sql injected with PDO.
Currently I'm stuck with using a variable inside a PDO query.
If I have two arguments like this
$rowsPerPage = 3;
// by default we show first page
$pageNum = 1;
if (isset($_GET['page'])) {
$pageNum = mysql_real_escape_string($_GET['page']);
}
$offset = ($pageNum - 1) * $rowsPerPage;
And I have query like this
$STH = $DBH->query("SELECT News.ID, LEFT(NewsText,650), Title, AID, Date, imgID," .
"DATE_FORMAT(Date, '%d.%m.%Y.') as formated_date " .
"FROM News, Categories, NewsCheck WHERE Name LIKE '%News - Block%' AND CID=Categories.ID AND JID=News.ID ".
"ORDER BY `Date` DESC LIMIT $offset, $rowsPerPage");
PDO reports an error in last line of the query ORDER BY
When I replace these line with
"ORDER BY Date DESC LIMIT3,3"); everything work.
So how to add variable values inside PDO::query ?
Updated:
Thanks to answer bellow I have updated my code like this
$STH = $DBH->prepare("SELECT News.ID, LEFT(NewsText,650), Title, AID, Date, imgID," .
"DATE_FORMAT(Date, '%d.%m.%Y.') as formated_date " .
"FROM News, Categories, NewsCheck WHERE Name LIKE '%News - Block%' AND CID=Categories.ID AND JID=News.ID ".
"ORDER BY `Date` DESC LIMIT :offset, :rowsPerPage;");
$STH->bindParam(':offset', $offset, PDO::PARAM_STR);
$STH->bindParam(':rowsPerPage', $rowsPerPage, PDO::PARAM_STR);
$STH->execute();
But error occured:
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 ''-3', '3'' at
line 1' in /pdo/test.php:42 Stack trace: #0
/pdo/test.php(42): PDOStatement->execute() #1 {main} thrown in
/pdo/test..
Second Update
Changed from PARAM_STR TO PARAM_INT like this
$STH->bindParam(':offset', $offset, PDO::PARAM_INT);
$STH->bindParam(':rowsPerPage', $rowsPerPage, PDO::PARAM_INT);
Everything works.
You want to use prepared statements and query parameters like the following:
$sth = $dbh->prepare('SELECT your_column FROM your_table WHERE column < :parameter');
$sth->bindParam(':parameter', $your_variable, PDO::PARAM_STR);
$sth->execute();
Using variables directly in your query will not protect you from SQL injections, even if you are using PDO. Parameters are the only good way to prevent them.

Categories