I have been doing this for quite a few queries but suddenly found one where it is not working. Here is my code:
$q = 'SELECT title FROM blog LIMIT :paging,:perpage';
$v = array(
':paging'=>(($page-1)*$perpage),
':perpage'=>$perpage
);
$sql = $conn->prepare($q);
$sql->execute($v);
if ($sql){
foreach($sql as $rs){
$title = $rs['title'];
echo '<article>'.$title.'</article>';
};
};
I am not getting any errors however It is also not displaying anything. When I take out $v and just put the values into the query like so:
$q = 'SELECT title FROM blog LIMIT '.(($page-1)*$perpage).','.$perpage.' ';
This works perfectly and outputs fields.
I have does this same array trick on many other queries in the past and never had any problems. Not sure what I did wrong here, need a fresh pair of eyes.
also $page = 1 and $perpage = 2
Its because when you use an array for execute, it defaults to PDO::PARAM_STR
, so it thinks its a string...which obviously doesn't play well with LIMIT
Instead use bindValue
, that way you can explicitly state PDO::PARAM_INT
$q = 'SELECT title FROM blog LIMIT :paging,:perpage';
$sql = $conn->prepare($q);
$sql->bindValue(':paging',(($page-1)*$perpage), PDO::PARAM_INT);
$sql->bindValue(':perpage',$perpage, PDO::PARAM_INT);
$sql->execute();
You need to use bindValues to bund the values to the query the use execute with no parameters!
You're not getting any PHP errors but you're not checking for SQL errors at all. You need to explicitly check for SQL errors.
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.