4

我有这段代码,它允许我插入一些我在数据库中选择的日期,现在这个只插入一个值,而不是全部,就像它停在第一个值..

你能告诉我我做错了什么吗?

谢谢!

$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);
}
4

3 回答 3

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);
于 2012-08-31T13:39:38.340 回答
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 注入并给您带来重大问题。看这个 还有mysql没有维护,建议改用MySqli或者PDO。

于 2012-08-31T13:29:03.593 回答
-1

尝试:

$sql = "INSERT INTO date SET job_id='".$job_id."', date='".$date."'";
mysql_query($sql);
于 2012-08-31T13:29:55.747 回答