1

I have a pdo statement to select rows and return them in an array. I am using pagination to display 12 results per page. If I directly input LIMIT 12, 12 , instead of LIMIT ?, ? the statement works correctly.

What am I doing wrong with the bindParam for both variables?

Both variables contain the correct data.

Heres the function I'm using:

// Retrieve active posts
function retrieve_active_posts(){
    //test the connection
    try{
        //connect to the database
        $dbh = new PDO("mysql:host=db2940.oneandone.co.uk;dbname=db348699391","xxx", "xxx");
    //if there is an error catch it here
    } catch( PDOException $e ) {
        //display the error
        echo $e->getMessage();

    }

    // Get all the posts
    $stmt = $dbh->prepare(" SELECT  p.post_id, post_year, post_desc, post_title, post_date, img_file_name, p.cat_id
                            FROM    mjbox_posts p
                            JOIN    mjbox_images i
                            ON      i.post_id = p.post_id
                                    AND i.cat_id = p.cat_id
                                    AND i.img_is_thumb = 1
                                    AND post_active = 1
                            ORDER BY post_date
                            DESC
                            LIMIT ?,?");
    $stmt->bindParam(1, $limit);
    $stmt->bindParam(2, $offset);                       
    $stmt->execute();


    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            $resultarray[] = $row;
    }

    return $resultarray;
}

Many thanks

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
crmepham
  • 4,676
  • 19
  • 80
  • 155
  • Can you add the output of `var_dump($limit, $offset);` ? – hek2mgl Apr 06 '13 at 16:33
  • @hek2mgl NULL NULL for both – crmepham Apr 06 '13 at 16:35
  • Incidentally, why loop over the resultset with `fetch()` to build an array when PDO provides [`fetchAll()`](http://php.net/manual/en/pdostatement.fetchall.php) for you? – eggyal Apr 06 '13 at 16:40
  • You can / should use `fetchAll()` if you just need to return the result array. Sometimes there are situation when it is nessesary to *touch* each record before returning it (for whatever reason). In such caes `fetch()` would fit. – hek2mgl Apr 06 '13 at 16:44
  • 1
    Also, I think you have the parameters ordered the wrong way around. The offset comes first, followed by the number of records to be returned (unless one includes the `OFFSET` keyword in which case the order is reversed). – eggyal Apr 06 '13 at 16:46

2 Answers2

4

Make sure that the type of $limit and $offset is set to PDO::PARAM_INT:

$limit = 20;
$offset = 0;

$stmt->bindParam(1, $limit,  PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Right after connect to the database, insert the following line of code:

$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);

Source: https://www.php.net/manual/en/pdo.setattribute.php

MMJ
  • 555
  • 4
  • 6