dqve65954 2013-04-02 17:04
浏览 64
已采纳

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?

  • 写回答

2条回答 默认 最新

  • dsc56927 2013-04-02 17:08
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向