开发者

PDO Mysql SQLSTATE[42000]

开发者 https://www.devze.com 2023-03-21 20:52 出处:网络
I\'ve built a function which will prepare SQL statement and execute it with given parameters. So here how it looks like:

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 violatio开发者_开发问答n: 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...).


I'm not sure why you're getting that message, but I'd say the problem is you're trying to use PDOStatement::bindParam(), which binds as a reference and only gets the value of the variable when you call PDOStatement::execute(), however by that time the original variable has been overwritten with a new value.

Either use PDOStatement::bindValue(), so the value is copied within the loop, or use unique variable references with bindParam.

0

精彩评论

暂无评论...
验证码 换一张
取 消