Dynamic prepared queries
You can build your query dynamically from $_POST array:
But, NEVER trust user input, which means you cannot trust that data in $_POST will contain valid column names.
1. Sanitize the post data
You can define an array of whitelisted column names $whitelist = array('field1', 'field2', ...)
, and then use:
$data = array_intersect_key($_POST, array_flip($whitelist));
to find the intersection between the whitelisted columns and your $_POST array. (Thanks @BillKarwin)
2. Build the query
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;
}
This will give you a SQL statement of the form:
$sql = INSERT INTO directory (field1, field2) VALUES (:field1, :field2)
and prepare the statement:
$stmt = $dbh->prepare($sql);
3. Bind parameters
You can then dynamically bind parameters to the placeholders:
foreach ($data as $placeholder => $value) {
$stmt->bindValue(":$placeholder", $value);
}
and execute it:
$stmt->execute();
A little more advanced...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…