$sqlArray = array();
$nameArray = array();
$valueArray = array();
foreach ($_POST as $name => $value) {
$nameArray[] = $name;
$valueArray[] = $value;
}
$names = implode(', ', $nameArray);
$values = implode(', ', ':'.$nameArray);
$sql = "INSERT INTO customers ( ".$names." ) VALUES ( ".$values." )";
print_r($sql);
$addRandom = $pdo->prepare( $sql );
foreach($_POST as $name => $value) {
$addRandom->bindValue($name, $value);
}
$boolean=$addRandom->execute();
if($boolean){
echo 'INSERTED';
}else{
echo 'FAILED';
}
我在运行此代码时遇到一些问题..请帮我修复此问题。在内爆中显示错误(',',':'。$ nameArray)
答案 0 :(得分:-1)
$fields = array_keys($_POST);
if (!empty($fields)) {
$names = implode('`, `', $fields);
$values = implode(', :', $fields);
$sql = "INSERT INTO customers ( `".$names."` ) VALUES ( :".$values." )";
print_r($sql);
$addRandom = $pdo->prepare($sql);
foreach ($fields as $field) {
$addRandom->bindValue(":{$field}", $_POST[$field]);
}
$boolean = $addRandom->execute();
if ($boolean){
echo 'INSERTED';
} else {
echo 'FAILED';
}
}