0

In my PDO implementation, I am attempting to use an inserted value in the limit clause of the SQL statement:

$sql = "SELECT * FROM table ORDER BY datetime DESC LIMIT :limit";
$params = array(":limit" => 5);
$query = $dbh->prepare($sql);
$query->execute($params);
$result = $query->fetchall(PDO::FETCH_ASSOC);

$params and $query are correctly returned, but $result is empty.

Upon running print_r($query->errorInfo);, I get the following:

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 ''5'' at line 1

How can I use PDO's insert values in this query? Am I doing it right?

Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73

2 Answers2

2

See PHP PDO bindValue in LIMIT

Basically, you need to cast the limit value to int using intval() when binding.

Community
  • 1
  • 1
J.C. Inacio
  • 4,442
  • 2
  • 22
  • 25
-1

You cannot bind variables into LIMIT clause’s operand (exactly, it probably depends on your database system vendor). Instead, use just string interpolation. :-(

$limit = 5;
$sql = "SELECT * FROM table ORDER BY datetime DESC LIMIT $limit";
$stmt = $dbh->query($sql);
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
minhee
  • 5,688
  • 5
  • 43
  • 81
  • Instead user string interpolation after carefully sanitising the $limit value if you're getting it from outside the system, e.g `$_GET['limit']` or something. – El Yobo Jun 03 '11 at 02:03
  • Unfortunate... However, string interpolation was what I was trying to avoid in the first place! – Julian H. Lam Jun 03 '11 at 02:05