简体   繁体   English

使用数组执行PDO返回null

[英]PDO execute with array returns null

I'm trying to use good PDO as always and almost everything works but one query: 我试图一如既往地使用良好的PDO,除了一个查询之外,几乎所有功能都可以使用:

$primary = 'my_id';
$table = 'my_table';
// This or...
$statement = $this->conn->prepare("SELECT MAX(:id) AS id FROM :table");
        $statement->bindParam(':id', $primary, PDO::PARAM_STR);
        $statement->bindParam(':table', $table, PDO::PARAM_STR);
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();

// This one. Both doesn't work.

$statement = $this->conn->prepare("SELECT MAX(:id) AS id FROM :table");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
$arr = array(
            ':id' => 'my_id',
            ':table' => 'my_table',
        );
        $statement->execute($arr);

These just return a null array. 这些只是返回一个空数组。 I feel so confused. 我感到很困惑。 So I have tried that: 所以我尝试过:

$statement = $this->conn->prepare("SELECT MAX(".$primary.") AS id FROM ".$table);
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $statement->execute();

And it works. 而且有效。 I feel like I'm missing something but can't figure it out. 我觉得我正在丢失某些东西,但无法弄清楚。 So clearly there's a problem with binding I tried different variations such as writing one of the variable manually, but no luck so far. 显然,绑定存在问题,我尝试了各种变体,例如手动编写变量之一,但到目前为止还算运气。

Thanks in advance for any help... 预先感谢您的任何帮助...

You can't use parameters as table names in PDO, so you will have to change this to avoid that. 您不能在PDO中将参数用作表名,因此必须对此进行更改以避免这种情况。 This is not a limitation of PDO, but a limitation of MySQL directly. 这不是PDO的限制,而是MySQL的直接限制。 The manual states that 手册指出

Parameter markers can be used only where data values should appear, not for SQL keywords, identifiers, and so forth. 参数标记只能用于应显示数据值的位置,而不能用于SQL关键字,标识符等。

Table and column names are identifiers, so using placeholders for them is not supported. 表名和列名是标识符,因此不支持使用占位符。 See this question for an alternative method. 有关其他方法,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM