为什么我不能将表名传递给准备好的PDO语句?
$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
var_dump($stmt->fetchAll());
}
Run Code Online (Sandbox Code Playgroud)
是否有另一种安全的方法将表名插入SQL查询?安全我的意思是我不想这样做
$sql = "SELECT * FROM $table WHERE 1"
Run Code Online (Sandbox Code Playgroud) 我正在使用PDO并希望做这样的事情:
$query = $dbh->prepare("SELECT * FROM :table WHERE :column = :value");
$query->bindParam(':table', $tableName);
$query->bindParam(':column', $columnName);
$query->bindParam(':value', $value);
Run Code Online (Sandbox Code Playgroud)
PDO是否允许我像这样绑定表名和列名?它似乎允许它,但即使我使用PDO :: PARAM_INT或PDO :: PARAM_BOOL作为数据类型,它也会在我的参数周围加上引号.
如果这不起作用,我怎样才能安全地转义我的变量,以便我可以在查询中插入它们?
注意:以下示例中的唯一区别是ORDER BY子句.
好代码:
$sql = 'SELECT [date], ? AS [name]
FROM [transactions]
WHERE [category_id] = 10
GROUP BY [date]
ORDER BY [date] ASC';
$stmt = $db->prepare($sql);
$stmt->bindValue(1, 'Test', PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
//returns rows in $data
Run Code Online (Sandbox Code Playgroud)
不好的代码:
$sql = 'SELECT [date], ? AS [name]
FROM [transactions]
WHERE [category_id] = 10
GROUP BY [date]
ORDER BY [date] ASC, [name] ASC';
$stmt = $db->prepare($sql);
$stmt->bindValue(1, 'Test', PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
//returns an empty array
Run Code Online (Sandbox Code Playgroud)
为什么我的第二段代码不起作用?如果我直接运行此查询的任一版本(在SQL Management Studio中),它可以以任何方式工作.如果我摆脱PHP中的问号并将值硬编码到查询中(而不是绑定它),那也是有效的!这里发生了什么? …
我在PDO语句中的ORDER BY子句中绑定参数时遇到问题.似乎没有将"orderBy"传递给查询,因为结果不是按照它们的预期排序的.当我使用诸如price查询中的列名 而不是参数时,结果按该列排序.代码是:
class Products {
const ORDER_BY_NAME='name';
const ORDER_BY_PRICE_PER_UNIT='price_per_unit';
const ORDER_BY_PRICE='price';
const ORDER_BY_MINIMUM_QUANTITY='minimum_quantity';
// function returns array of all products
public function getAllProducts($orderBy) {
$db=Registry::getVariable('db');
$pdoStatement=$db->prepare("SELECT name, minimum_quantity, price_per_unit, price, id FROM products ORDER BY :orderBy;");
$pdoStatement->bindParam(':orderBy', $orderBy, PDO::PARAM_STR);
$pdoStatement->execute();
return $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
}
}
Run Code Online (Sandbox Code Playgroud)
后来我打电话给:
$products=new Products();
echo $products->getAllProducts(Products::ORDER_BY_PRICE);
Run Code Online (Sandbox Code Playgroud)
为什么不在命令中使用:orderBy参数?