我试图通过重新利用我的插入脚本来节省我的项目时间,所以我改变了
此
if ( !empty($_POST)) {
// keep track post values
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO customers (name,email,mobile) values(?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$mobile));
Database::disconnect();
header("Location: index.php");
}
}
对此:
if (!empty($_POST)){
function filter($data){
$data=trim(htmlentities(strip_tags($data)));
return $data;
}
foreach($_POST as $key => $value){
//Create variables with the same name as the fields and sanitize with filters
$$key = filter($value);
//1 - Case <checkbox>
if(is_array($value)){
//Get field value and save in array prepKey
$prepKey[] = filter(implode(",",$value));
}
//2 - Case <input>
if(!is_array($value)){
//Get field value and save in array prepKey
$prepKey[] = filter($value);
}
//Get field name and save in array prepField
$prepField[] = $key;
}
//Transform field array to comma separated string ex: name,email,address
$field = implode (",", $prepField);
//Count inputs
$count_post = count($_POST);
//Prepare interrogations signs and save on array prepInt for PDO ex:?
for($i=1;$i<=$count_post;$i++){
$prepInt[] = "?";
}
//Transform interrogations array to comma separated string ex: ?,?,?
$int = implode (",", $prepInt);
// insert data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO customers ($field) values($int)";
//SQL become "INSERT INTO customers (name,email,address) values (?,?,?) ";
$q = $pdo->prepare($sql);
$q->execute($prepKey);
//prepKey become 'array($name,$email,$address)'
Database::disconnect();
header("Location: index.php");
}
代码对我的所有表单来说都像一个魅力,但我不确定这个方法是不是危险或容易受到攻击。