PHP选择列表 - 在数据库中插入多个值
I'm trying to insert multiple values in the database using select list. What I got so far:
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]]')");
}
Unfortunately it doesn't work, I tried to print $cars to check the resulted value. It prints "Array", and when I tried to print $cars[$i] it prints nothing.
Does anyone know what the problem is?
我正在尝试使用选择列表在数据库中插入多个值。 到目前为止我得到了什么: p>
HTML p>
&lt; form enctype =“multipart / form-data”action =“”method = “post”&gt;
&lt; select name =“cars []”multiple =“multiple”style =“width:300px”&gt;
&lt;?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'];
?&gt; \ n&lt; option value =“&lt;?php echo $ car_id?&gt;”&gt;&lt;?php echo $ car_name?&gt;&lt; / option&gt;
&lt;?php}?&gt;
&lt; / 选择&gt;&lt; br /&gt;
&lt; input type =“submit”name =“submit”value =“提交”/&gt;&lt; br /&gt;
&lt; / form&gt;
code> pre>
PHP p>
$ cars = $ _POST ['cars'];
echo $ cars; \ n for($ i = 0; $ i&lt; count($ cars); $ i ++){
echo $ cars [$ i];
$ carGroups = mysql_query(“INSERT INTO car_groups VALUES('$ company', '$汽车[$ i]]')“);
}
code> pre>
不幸的是它不起作用,我试图打印$ cars来检查结果值。 它打印“数组”,当我试图打印$ cars [$ i]时,它什么都不打印。 p>
有谁知道问题是什么? p>
div >
There is an extra closing bracket that should be removed. You are not checking if your query was successful or not.
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
should be:
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]')") or die(mysql_error());
Since $cars is an array, you can print its content using print_r or var_dump:
print_r($cars);
var_dump($cars);
Useful reading:
How to get useful error messages in PHP?
mysql_* functions are deprecated
You have error $cars[$i]] and need change $cars[$i]
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
fix php for you with good sql
$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}'");
}