我正在尝试使用选择列表在数据库中插入多个值。到目前为止我得到了什么:
HTML
<form enctype="multipart/form-data" action="" method="post">
<select name="cars[]" multiple="multiple" style="width:300px">
<?php
$getcars = mysql_query("SELECT cars_id, cars_name FROM car");
while ($row = mysql_fetch_assoc($getcars)) {
$car_id = $row['cars_id'];
$car_name = $row['cars_name'];
?>
<option value="<?php echo $car_id ?>"><?php echo $car_name ?></option>
<?php } ?>
</select><br />
<input type="submit" name="submit" value="Submit"/><br/>
</form>
PHP
$cars= $_POST['cars'];
echo $cars;
for($i = 0; $i < count($cars); $i++){
echo $cars[$i];
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
}
不幸的是它不起作用,我试图打印$ cars来检查结果值。它打印“阵列”,当我试图打印$ cars [$ i]时,它什么都不打印。
有谁知道问题是什么?
答案 0 :(得分:1)
应该删除一个额外的右括号。您没有检查您的查询是否成功。
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
应该是:
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]')") or die(mysql_error());
由于$ cars是一个数组,您可以使用print_r或var_dump打印其内容:
print_r($cars);
var_dump($cars);
有用的阅读:
How to get useful error messages in PHP?
mysql_* functions are deprecated
答案 1 :(得分:0)
你有错误$ cars [$ i]]并且需要更改$ cars [$ i]
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
使用好的SQL修复php
$cars= $_POST['cars'];
echo $cars;
foreach($cars as $i => $cars_name){
echo $cars_name;
$carGroups = mysql_query("INSERT INTO car_groups SET `fieldcompany`='{$company}', `fieldcars`='{$cars_name}'");
}