简体   繁体   中英

PHP MySQL PDO syntax error in Bindparam

Hi I'm trying to select some random rows from table using MySQL PDO using PHP

$query = $conn->prepare("SELECT * FROM `products` WHERE `cat` = :cat ORDER BY RAND() LIMIT :limit_to");

$query->bindParam(':limit_to', $limit, PDO::PARAM_INT);
$query->bindParam(':cat', $cat, PDO::PARAM_INT);
$stmt = $query->execute();

However this throws a mysql syntax error like this,

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

What's causing this error and why? I don't see anything wrong in the

The problem is that when you do $limit = $_REQUEST['limit']; , variable $limit has type string .

For example (both contains number, but variable type is different):

$varInt = 2;
$varString = "2";

var_dump ($varInt);
var_dump ($varString);

prints:
    int 2
    string '2' (length=1)

So your prepared statement becomes to be bound with:

$limit = $_REQUEST['limit']; // $_REQUEST['limit'] = 2
$cat = 3;

SELECT * FROM `products` WHERE `cat` = :cat ORDER BY RAND() LIMIT :limit_to

Bound with :limit_to='2', :cat='3'

The problem is in LIMIT syntax. Symbols '' breaks the syntax. You must be sure that you bind integer variable to $limit.

// do it in first place you have access to $_REQUEST['limit'] or other global arrays , for example $_GET, $_POST

$limit = intval($_REQUEST['limit']); // $_REQUEST['limit'] = 2
 $cat = intval($blablabla); // or from any other source

$query = $conn->prepare("SELECT * FROM products WHERE 
                         cat = :cat ORDER BY RAND() 
                                    LIMIT :limit_to");

$query->bindValue(':limit_to', $limit, PDO::PARAM_INT);
$query->bindValue(':cat', $cat, PDO::PARAM_INT);
$stmt = $query->execute();

ps Use bindValue() , it's better in 99% cases.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM