問題描述
我有一個包含大約 25 個輸入字段的大表單.
I have a large form with about 25 input fields.
我正在嘗試將它們插入我的表格中,而我知道如何使用以下內容的唯一方法...
Im trying to insert them into my table and the only way i know how is using the following...
$count = $dbh->exec("INSERT INTO directory(field1, field2) VALUES (':value1', ':value2')");
由于我有這么多帖子變量,有沒有比在我的查詢中輸入每個人更好的方法呢?
As I have so many post variables, is there a better way to do this than type each and everyone into my query?
推薦答案
動態準備查詢
您可以從 $_POST 數組動態構建查詢:
Dynamic prepared queries
You can build your query dynamically from $_POST array:
但是,永遠不要相信用戶輸入,這意味著您不能相信 $_POST 中的數據將包含有效的列名.
But, NEVER trust user input, which means you cannot trust that data in $_POST will contain valid column names.
1.清理帖子數據
可以定義一個白名單列名數組$whitelist = array('field1', 'field2', ...)
,然后使用:
You can define an array of whitelisted column names $whitelist = array('field1', 'field2', ...)
, and then use:
$data = array_intersect_key($_POST, array_flip($whitelist));
找到列入白名單的列和您的 $_POST 數組之間的交集.(感謝@BillKarwin)
to find the intersection between the whitelisted columns and your $_POST array. (Thanks @BillKarwin)
2.構建查詢
private function buildInsertSql($data, $table) {
$columns = "";
$holders = "";
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= $column;
$holders .= ($holders == "") ? "" : ", ";
$holders .= ":$column";
}
$sql = "INSERT INTO $table ($columns) VALUES ($holders)";
return $sql;
}
這將為您提供以下形式的 SQL 語句:
This will give you a SQL statement of the form:
$sql = INSERT INTO directory (field1, field2) VALUES (:field1, :field2)
并準備聲明:
$stmt = $dbh->prepare($sql);
3.綁定參數
然后您可以將參數動態綁定到占位符:
You can then dynamically bind parameters to the placeholders:
foreach ($data as $placeholder => $value) {
$stmt->bindValue(":$placeholder", $value);
}
并執行它:
$stmt->execute();
<小時>
更高級一點...
- 看看這個鏈接 綁定到相同的占位符有關如何使您的動態準備好的語句更加健壯的信息.
- 看看這個鏈接:綁定參數內部循環 有關在循環中綁定參數與值的警告.
- Take a look at this link Binding to the same placeholder For information about how to make your dynamic prepared statement more robust.
- Take a look at this link: Bind Params Inside Loop For a caveat regarding binding paramaters vs values in a loop.
A little more advanced...
這篇關于使用 PDO 將大量變量插入表中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!