Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO -> Prepared query returning error ( same query not prepared working fine )

I use the following sql to get the value value of the field que_id of a specific line of my table and it is working fine. Do note that que_id(auto-incremented) and line numbers is not the same.

$qry_que_getid = $connexion->query('SELECT somefield FROM table ORDER BY somefield ASC LIMIT '.$lineNumberSeeked.', 1');

$row = $qry_que_getid->fetch(PDO::FETCH_ASSOC); 
echo $row['que_id'];

When I try to transform that query into a prepared query as follows I have an error and I do not get it:

$qry_que_getid = $connexion->prepare('SELECT somefield FROM table ORDER BY somefield ASC LIMIT ?, 1');

$qry_que_getid->execute(array(4));

$row = $qry_que_getid->fetch(PDO::FETCH_ASSOC); 
echo $row['que_id'];

I get the following error SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''3', 1' at line 1

Hope somene can help me understand. Thank you in advance. Cheers. Marc.

like image 425
Marc Avatar asked May 07 '12 16:05

Marc


1 Answers

From the PHP manual at http://www.php.net/manual/en/pdostatement.execute.php:

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

The LIMIT clause is expecting an integer I believe so you should use the bindParam() method instead.

$limit = 4;
$qry_que_getid->bindParam(1, $limit, PDO::PARAM_INT);
$qry_que_getid->execute();

Otherwise, the parameter will be passed as type PDO::PARAM_STR instead of the expected PDO::PARAM_INT.

like image 148
Cowlby Avatar answered Sep 24 '22 19:09

Cowlby