PHP选择列表-在数据库中插入多个值 [英] PHP Select List - Insert multiple values in database
问题描述
我正在尝试使用选择列表在数据库中插入多个值.到目前为止,我得到了什么:
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]]')");
}
不幸的是,它不起作用,我试图打印$ cars来检查结果值.它打印"Array",当我尝试打印$ 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?
推荐答案
还有一个额外的结束括号应删除.您不检查查询是否成功.
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]]')");
应该是:
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]')") or die(mysql_error());
由于$ cars是一个数组,因此可以使用 print_r 或
Since $cars is an array, you can print its content using print_r or var_dump:
print_r($cars);
var_dump($cars);
有用的读物:
如何在PHP中获得有用的错误消息?
不建议使用mysql_ *函数
Useful reading:
How to get useful error messages in PHP?
mysql_* functions are deprecated
这篇关于PHP选择列表-在数据库中插入多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!