How to apply bindValue method in LIMIT clause with PHP?

Spread the love

Sometimes, we want to apply bindValue method in LIMIT clause with PHP.

In this article, we’ll look at how to apply bindValue method in LIMIT clause with PHP.

How to apply bindValue method in LIMIT clause with PHP?

To apply bindValue method in LIMIT clause with PHP, we convert the value we use with limit into an integer.

For instance, we write

$fetchPictures = $PDO->prepare("SELECT * 
    FROM pictures 
    WHERE album = :albumId 
    ORDER BY id ASC 
    LIMIT :skip, :max");

$fetchPictures->bindValue(':albumId', $_GET['albumid'], PDO::PARAM_INT);

if(isset($_GET['skip'])) {
    $fetchPictures->bindValue(':skip', (int) trim($_GET['skip']), PDO::PARAM_INT);
} else {
    $fetchPictures->bindValue(':skip', 0, PDO::PARAM_INT);  
}

$fetchPictures->bindValue(':max', $max, PDO::PARAM_INT);
$fetchPictures->execute() or die(print_r($fetchPictures->errorInfo()));
$pictures = $fetchPictures->fetchAll(PDO::FETCH_ASSOC);

to write

$fetchPictures->bindValue(':skip', (int) trim($_GET['skip']), PDO::PARAM_INT);

to bind the value of the :skip placeholder to the $_GET array’s skip value.

We convert it to an int with (int) so that there won’t be any data type errors when calling bindValue.

Conclusion

To apply bindValue method in LIMIT clause with PHP, we convert the value we use with limit into an integer.

Leave a Reply

Your email address will not be published. Required fields are marked *