Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with mysql LIMIT and PDO

Tags:

php

mysql

pdo

Trying to do the dreaded pagination using PDO, but I can't find an answer fitting my situation:

    $pageVar = 10;
    $startRowLimit = ($page * $pageVar) - $pageVar; // returns correct value 

$articlesQuery = "SELECT 
`ID`,`Title`,`Text`,`Poster`,`Date`,
( SELECT `ID` FROM users WHERE article.`Poster` = users.`Username` )
FROM article WHERE `Visible` = 1 ORDER BY `Date` DESC LIMIT ? , ? ";

$articles = $mysqli->selectAll($articlesQuery, array($startRowLimit, $pageVar));

Here's selectAll function:

        public function selectAll($query, $params){

        $this->sql = $this->dbh->prepare($query);
        $this->sql->execute($params);
        $result = $this->sql->fetchAll(PDO::FETCH_ASSOC);

        return $result;

    }

How can I make it work? I tried doing

array((int) $startRowLimit, (int) $pageVar)

But that doesn't work. Any idea?

like image 928
Crembo Avatar asked Jun 21 '11 10:06

Crembo


1 Answers

You don't need to use mark for limit since they doens't come from user input. Just put your int variables in the query

DESC LIMIT {$offset} , {$var}

Anyway the right syntax is:

$sql = "SELECT * [...] LIMIT :start, :results";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':start', $_GET['start'], PDO::PARAM_INT);
$stmt->bindParam(':results', $_GET['results'], PDO::PARAM_INT);
like image 127
dynamic Avatar answered Sep 22 '22 03:09

dynamic