I’ve built a function which will prepare SQL statement and execute it with given parameters. So here how it looks like:
function go($statement) {
$q = self::$connection->prepare($statement, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
for($i = 1; $i < func_num_args(); $i++) {
$arg_to_pass = func_get_arg($i);
$q->bindParam($i, $arg_to_pass, PDO::PARAM_INT);
}
$q->execute();
}
But when I call it, it gives me the following error:
Fatal error: Uncaught exception ‘PDOException’ with message
‘SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax;
However, this two variants are working perfectly:
function go($statement) {
$q = self::$connection->prepare($statement, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
for($i = 1; $i < func_num_args(); $i++) {
$q->bindValue($i, func_get_arg($i), PDO::PARAM_INT);
}
$q->execute();
}
(This one is stupid, but just for test)
function go($statement) {
$q = self::$connection->prepare($statement, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$arg_to_pass = func_get_arg(1);
$q->bindParam(1, $arg_to_pass, PDO::PARAM_INT);
$arg_to_pass2 = func_get_arg(2);
$q->bindParam(2, $arg_to_pass2, PDO::PARAM_INT);
$q->execute();
}
So why bindParam doesn’t work inside a loop?
I’m guessing it’s because you’re breaking the binding – you fetch an argument into
$arg_to_pass, and then bind it. On the next iteration, you fetch another arg into the same variable (which is now bound as parameter #1) and try to rebind it as parameter #2. The other versions all use unique argument names (the direct return value from func_get_args, different var names, etc…).