[英]Php PDO, letting users also define the field to select
我正在嘗試創建一個函數,從表中選擇所有數據,用戶在其中定義字段和值。 像這樣:
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中讓用戶也選擇表格的字段和值。
謝謝。
您不能使用占位符作為標識符 (即字段名稱); 僅用於數據 。 您只能制作允許的字段名稱的白名單:
$allowed = array('name', 'date', 'price');
if (!in_array($field, $allowed, true)) {
throw new InvalidArgumentException;
}
$query = $this->db->prepare("SELECT * FROM `users` WHERE $field = ?");
你不能使用參數?
在字段名稱中。
表和列名稱不能由PDO中的參數替換。 在這種情況下,您只需手動過濾和清理數據。 來源 。
要直接允許用戶字段編輯,您可以執行以下操作:
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;
}
這將動態查找表的字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.