dongyanzhui0524 2011-07-17 13:29
浏览 8
已采纳

带有$ i和$ _POST值的SQL循环

I am trying to loop through a number of results from a form, but can't get it quite right.

  for ($i=1;$i<$total;i++)
    {
     mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}','{$_POST['$iH']}', '{$_POST['$iA']}'");
    }

I want $_POST['$iH'] to be the same as $_POST['1H'],$_POST['2H'], $_POST['3H'] etc.

  • 写回答

3条回答 默认 最新

  • dongnan4571 2011-07-17 13:35
    关注

    Like so:

    for ($i = 1; $i < $total; $i++) { // <--- You had a typo here
       $sql  = "INSERT INTO MYSQL(value1,value2,value3) ";
       $sql .= "VALUES('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
       mysql_query($sql);
    }
    

    But, two big problems.

    Multiple queries

    Boy, what a waste! Dispatch one instead:

    $rows = Array();
    for ($i = 1; $i < $total; $i++) {
       $rows[] = "('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
    }
    
    $sql  = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
    mysql_query($sql);
    

    SQL injection

    It continues to baffle me how, in 2011, people are still not getting this.

    If you're going to insist upon using the ancient mysql API (not even the OO version?!) rather than PDO, get into the habit of sanitising your inputs:

    $rows = Array();
    for ($i = 1; $i < $total; $i++) {
       $rows[] = "('{$i}'," . 
                 "'" . mysql_escape_string($_POST[$i . 'H']) . "'," .
                 "'" . mysql_escape_string($_POST[$i . 'A']) . "')";
    }
    
    $sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
    mysql_query($sql);
    

    OK, so without multi-query support in your API it's unlikely to cause you significant grief here, but it can do in authentication routines. Just get used to scripting properly in this regard.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部