我有这个代码允许我在数据库中插入一些我选择的日期,现在这个只插入一个值,而不是全部,就像它停在第一个值一样。
你能告诉我我做错了什么吗?
谢谢!
$job_id=$_REQUEST['job_id'];
$dates = explode(",", $_POST['altField']);
foreach($dates as $date){
$sql="INSERT INTO date (job_id,date) VALUES('$job_id','$date')";
mysql_query($sql);
}
答案 0 :(得分:1)
$job_id=$_REQUEST['job_id'];
$dates = explode(",", $_POST['altField']);
$values_arr = array();
foreach ($dates as $date) {
$values_arr[] = "('" . $job_id . "','" . $date . "')";
}
$values = implode(", ", $values_arr);
$sql="INSERT INTO date (job_id,date) VALUES $values";
mysql_query($sql);
答案 1 :(得分:0)
$job_id=$_REQUEST['job_id'];
$dates = explode(",", $_POST['altField']);
foreach($dates as $date){
$values .= '("'.$job_id.'","'.$date.'"),';
}
$sql="INSERT INTO date (job_id,date) VALUES " . substr($values, 0, -1);
mysql_query($sql);
插入可以有多个值集,因此您只需要在foreach中设置值,然后在其外部进行查询。你也可以这样做,得到相同的结果,
$job_id=$_REQUEST['job_id'];
$dates = explode(",", $_POST['altField']);
foreach($dates as $date){
$values[] = '("'.$job_id.'","'.$date.'")';
}
$sql="INSERT INTO date (job_id,date) VALUES " . implode(',',$values);
mysql_query($sql);
<强>提醒强>
始终清理您的输入。不这样做可能导致SQL注入并导致重大问题。看看this还没有维护mysql,建议切换到MySqli或PDO。
答案 2 :(得分:-1)
尝试:
$sql = "INSERT INTO date SET job_id='".$job_id."', date='".$date."'";
mysql_query($sql);