Reputation: 31580
number of bound variables does not match number of tokens … on line 54
I'm trying to use a function to build a pdo prepared query, but I'm getting all kinds of errors.
23 function get_type($a) {
24 if (is_numeric($a)) return $record_data->bindParam(":value", $a, PDO::PARAM_INT); // $a is a number
25 if (strlen($a)<1) return $record_data->bindParam(":value", "", PDO::PARAM_STR); // $a is empty
26 return $record_data->bindParam(":value", $a, PDO::PARAM_STR); // default
27 }
…
51 foreach($pair as $qstn=>$answr) {
52 $record_data = $dbh->prepare("SOME_SQL");
53 get_type($answr);
54 $record_data->execute();
55 }
It was working before I put the bindParam
s into a function…I'm guessing it has something to do with the return
?
Upvotes: 0
Views: 88
Reputation: 237865
The problem is due to the function's scope. Variables from outside a function are only usable within it if (a) they are passed in as arguments or (b) if they are imported using the global
statement. The latter is a very bad idea.
You need to pass the statement object to your function as well as the value you want to bind:
function get_type($record_data, $a) {
// ...
get_type($record_data, $answr);
With that said, your code looks very broken. The idea of determining whether the value should be passed as an integer or a string based on its type in the application (rather than the column type of the database) seems wrong to me. Also, you do a foreach
, but only the last item in the array will be used, since you are only binding to one parameter (:value
). You almost certainly need to rethink your whole approach here.
Upvotes: 1