dongwopu8210 2015-09-04 21:54
浏览 48
已采纳

在foreach里面插入mysql是不行的?

I'm trying to figure out why this MYSQL INSERT inside the foreach doesn't insert anything into mysql database!

   // Parse the form data and add inventory item to the system
    if (isset($_POST['g_name'])) {


        $g_name =$_POST['g_name'];
        $numbers = $_POST['numbers'];

        $comma_separated = explode(", ", $numbers);


        foreach($comma_separated as $seperate){

        $sql .="INSERT INTO groups(`g_name`, `numbers`) VALUES ('$g_name','$seperate')";

        }

$query = mysqli_query($db_conx, $sql);
        header("location: groups.php"); 
        exit();
    }

if I change the $sql .= to $sql = it inserts only one value in the MYSQL database.

the value of $numbers is like this: 1, 2, 3, 4, 5

could someone please advise on this issue?

any help would be appreciated.

  • 写回答

3条回答 默认 最新

  • dqby43944 2015-09-04 21:59
    关注

    Change your loop so you execute the query each time:

    foreach($comma_separated as $seperate){
    
        $sql ="INSERT INTO groups(`g_name`, `numbers`) VALUES ('$g_name','$seperate')";
        $query = mysqli_query($db_conx, $sql);
    }
    

    You should keep in mind that your script is at risk for SQL Injection Attacks. Learn about prepared statements.

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

报告相同问题?

悬赏问题

  • ¥15 手机连接电脑热点显示无ip分配
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大