如果每個列類型爲PDO::PARAM_STR
,那麼它是相當簡單的爲您的參數綁定使用PDOStatement::execute unamed放慢參數標記。但是,如果列類型有所不同,那麼當您使用PDOStatement::bindParam綁定到每列時,您需要指定每列的列類型。
從似乎是用戶輸入的表中接受表名和列名不是一個好主意。如果表名或列名不正確,查詢將會失敗,但您需要非常小心以確保表和列名可以安全使用。以下示例在執行任何SQL之前檢查表和列名稱與白名單:
function insert($postValues, $table) {
$dbh = $this->connect();
// Create a simple whitelist of table and column names.
$whitelist = array('my_table' => array('col1', 'col2', 'col3'));
// Check if the table name exists in the whitelist.
if(!array_key_exists($table, $whitelist)) {
exit("$table is not a valid table name.\n");
}
// Count the number of columns that are found in the whitelist.
$cols = count(
array_intersect(
$whitelist[$table],
array_keys($postValues)));
if($cols !== count($postValues)) {
exit("One or more invalid column names have been supplied.\n");
}
// Create a comma separated list of column names.
$columns = implode(', ', array_keys($postValues));
// Create a comma separated list of unnamed placeholders.
$params = implode(', ', array_fill(0, count($postValues), '?'));
// Create a SQL statement.
$sql = "INSERT INTO $table ($columns) VALUES ($params)";
// Prepare the SQL statement.
$stmt = $dbh->prepare($sql);
// Bind the values to the statement, and execute it.
return $stmt->execute(array_values($postValues));
}
echo insert(
array(
'col1' => 'value1',
'col2' => 'value2',
'col3' => 'value3'),
'my_table');
// 1
echo insert(
array(
'col1' => 'value1',
'col2' => 'value2',
'col3' => 'value3'),
'unsafe_table');
// unsafe_table is not a valid table name.
echo insert(
array(
'col1' => 'value1',
'col2' => 'value2',
'unsafe_col' => 'value3'),
'my_table');
// One or more invalid column names have been supplied.
但是,可以從文檔(http://php.net/manual/en/pdo.quote .php),你最好使用prepare()。您可以使用佔位符輕鬆動態地創建一個sql字符串,並隨後調用bindParam/bindValue將它們綁定到該語句。 – 2010-07-21 11:46:10
是的,確實如此。雖然如果我遍歷我的'$ _POST'數據(或者我使用的任何數組),我也可以對數據進行操作。例如,在查詢或鍵/值對中使用哈希密碼之前,如果我正在更新並且用戶沒有輸入任何內容作爲其新密碼,那麼哈希密碼就完全相同。如果我沒有刪除密鑰,則會清空一個空字符串並破壞用戶的登錄。只是想一想。 – 2010-07-21 11:55:04
@Dennis:不幸的是,您不能輕鬆地將數組值綁定到預準備語句。所以上面的方法是可以的。當然,您可以動態構建準備好的SQL語句(根據需要添加儘可能多的佔位符),然後將每個數組項綁定到此語句。 – 2010-07-21 11:56:56