PDO error with variable in LIMIT

1

In PDO today was the first time I had to by a variable in LIMIT, and I'm getting this error:

  

Fatal error: Uncaught exception 'PDOException' with message   'SQLSTATE [HY093]: Invalid parameter number: number of bound variables   does not match the number of tokens   filename.php: 85 Stack trace: # 0   filename.php (85):   PDOStatement-> Run (Array) # 1 {main} thrown in   filename.php on line 85

Line 85 is this:

$sql2->execute(array(":idQuiz" => $idQuiz));

My code:

$perguntaQuiz = 2;
$sql2 = $pdo->prepare('SELECT * FROM quiz_pergunta WHERE idquiz = :idQuiz ORDER BY id ASC LIMIT 0, :perguntaQuiz');
$sql2->bindParam(':perguntaQuiz', $perguntaQuiz, PDO::PARAM_INT); 
$sql2->execute(array(":idQuiz" => $idQuiz));

What am I missing?

    
asked by anonymous 12.08.2016 / 18:17

2 answers

4

The error informs that one of the parameters reported is no value to be replaced. Let's see:

$perguntaQuiz = 2;
$sql2 = $pdo->prepare('SELECT * FROM quiz_pergunta WHERE idquiz = :idQuiz ORDER BY id ASC LIMIT 0, :perguntaQuiz');
$sql2->bindParam(':perguntaQuiz', $perguntaQuiz, PDO::PARAM_INT); 
$sql2->execute(array(":idQuiz" => $idQuiz));

In your select you enter the binds :idQuiz and :perguntaQuiz but there is only one method bindParam declared, you entered the second, within method execute .

Change to:

$perguntaQuiz = (int)2;
$idQuiz = (int)2;

$sql2 = $pdo->prepare('SELECT * FROM quiz_pergunta WHERE idquiz = :idQuiz ORDER BY id ASC LIMIT 0, :perguntaQuiz');
$sql2->bindParam(':perguntaQuiz', $perguntaQuiz, PDO::PARAM_INT); 
$sql2->bindParam(':idQuiz', $idQuiz, PDO::PARAM_INT); 
$sql2->execute();
    
12.08.2016 / 18:40
3

This error means you have not passed the values for all bookmarks.

$sql2 = $pdo->prepare('SELECT * FROM quiz_pergunta WHERE idquiz = :idQuiz ORDER BY id ASC LIMIT 0, :perguntaQuiz');

The markers are these parameters that start with:, in case you have 2 of them :idQuiz and :perguntaQuiz the PDO of preference to the parameters that you pass in execute() , as in execute() only has 1 :idQuiz he gives this error.

You have to pass the values on one or the other.

No bindParam

$sql2->bindParam(':perguntaQuiz', $perguntaQuiz, PDO::PARAM_INT); 
$sql2->bindParam(':idQuiz', $idQuiz, PDO::PARAM_INT); 

Or no execute()

$sql2->execute(array(":perguntaQuiz"=>$perguntaQuiz, ":idQuiz" => $idQuiz));
    
12.08.2016 / 18:42