You are already using the PDO library, which is good for starters, however you aren't exactly utilizing the communication method as it would be adequate:
$sqlArray = array();
$nameArray = array();
$valueArray = array();
$insertSQL = "INSERT INTO random ([[tablename]]) VALUES (?);";
$whiteList = array(
'random1',
'random2',
'zipCode',
...
);
function whiteListedColumn($whiteList, $columnName){
if (in_array($columnName, $whiteList)){
return true;
}
return false;
}
function prepareStatement($dbHandler, $templateSQL, $columnName){
$completeSQL = str_replace('[[tablename]]', $columnName, $templateSQL);
return $dbHandler->prepare($completeSQL);
}
try{
foreach($_POST AS $name => $value) {
if (whiteListedColumn($whiteList, $name)){
$prepStmt = prepareStatement($dbh, $insertSQL, $name);
$prepStmt->execute(array($value));
}
}
}catch(Exception $e){
echo "Error has occured while inserting data.";
}
I've refactored the insert query to incorporate a wild-card binder which we will be using at the execute
step (passing in an array of values to be bound to the appropriate places in the query indicated by ?
marks).
You are passing in the colum names, so to sanitize them, we aren't going to take the route of manually escaping any bad characters, but we will take the route of comparing the input to a whitelist of accepted column names predefined - that way, anything that is 1) not threatening the consistency of your database, 2) semantically valid for your database will be allowed, everything else will result in the execute portion absolutely neglected.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…