我正在尝试创建一个从表中选择所有数据的函数,用户在其中定义字段和值。像这样:
public function fetch($field, $value){
$query = $this->db->prepare("SELECT * FROM `users` WHERE ? = ?");
$query->bindValue(1, $field);
$query->bindValue(2, $value);
try{
$query->execute();
} catch(PDOException $e){
die($e->getMessage());
}
return $query->fetch();
}
我没有得到任何回报,甚至没有错误。有人可以告诉我我做错了什么,或者甚至可以在PDO中让用户也选择表格的字段和值。
谢谢。
答案 0 :(得分:3)
您不能将占位符用于标识符(即字段名称);仅适用于数据。您只能制作允许的字段名称的白名单:
$allowed = array('name', 'date', 'price');
if (!in_array($field, $allowed, true)) {
throw new InvalidArgumentException;
}
$query = $this->db->prepare("SELECT * FROM `users` WHERE $field = ?");
答案 1 :(得分:1)
您不能在字段名称中使用参数?
。
表和列名称不能由PDO中的参数替换。在这种情况下,您只需手动过滤和清理数据。 Source
要直接允许用户字段编辑,您可以执行以下操作:
public function fetch($field, $value){
// To avoid injection
if (!in_array($field, array('these', 'are', 'field', 'names')))
echo "Sorry, that's not a valid field";
else
{
$query = $this->db->prepare("SELECT * FROM `users` WHERE `" . $field . "` = ?");
$query->bindValue(1, $value);
try{
$query->execute();
} catch(PDOException $e) {
die($e->getMessage());
}
}
return $query->fetch();
}
此外,我有一个小功能(实际上是一种方法)来自动完成这项工作:
// Validate the cols names.
private function setCols($TableName)
{
// If this script is still running, $this->Table exists in database and it's sane
$Cols = array();
$STH = $this->DB->query('SHOW COLUMNS FROM `' . $this->Table . '`');
foreach ($STH->fetchAll() as $Name)
$Cols[] = $Name[0];
$this->Columns = $Cols;
}
这将动态找到表格的字段。