将变量和字符串连接为表名的 PDO 查询


PDO query with variable and string concatenated as table name

我有这个查询

$prefix = 'de_';
    $sql = "INSERT INTO $prefix.request_products (created_at, request_id) VALUES (NOW(), :request_id)";

这将起作用,但是php或PDO(或两者)正在查询中写入点,表名de_request_products但查询是构建为de_.request_products

如果我只在$prefix和字符串 PDO 之间使用空格,则会引发错误。

是否有任何其他可能性如何在查询中连接字符串和变量,或者这是像这样构建它的唯一方法:

$prefix = 'de_';
$table = 'request_products';
$concat = $prefix.$table;
$sql = INSERT INTO $concat ...

使用${variable}语法:

$sql = "INSERT INTO ${prefix}request_products (created_at, request_id) VALUES (NOW(), :request_id)";
这里的

手册:http://php.net/manual/pl/language.types.string.php说:"将变量名称括在大括号中以显式指定名称的结尾。所以这应该让你开心:

$prefix = 'de_';
$sql = "INSERT INTO ${prefix}request_products (created_at, request_id) VALUES (NOW(), :request_id)";