简体   繁体   English

当我有复选框中的数组时,MySQL foreach INSERT。

[英]MySQL foreach INSERT when I have an array from checkboxes.

I have a list of checkboxes that I want to insert into a database, which I have processed as an array: 我有一个要插入数据库的复选框列表,该复选框已作为数组处理:

<input name="my_array[]" value="<?php echo $data['ID'] ?>" type="checkbox">
<?php echo $data['name'] ?><?php echo "br/>";

I'm getting my list of checkboxes from my database, and the selected checkboxes are being posted like so: 我正在从数据库中获取复选框列表,并且所选复选框的发布方式如下:

   $strFoo=$_POST['my_array'];

    $strBar = "";


    foreach ($strFoo as $strFooName) {

    $strBar .= $strFooName . ", ";
    }
    $strBar = substr($strBar, 0, -2);

Echoing, I get my list of ID's selected like so 1, 2, 3, 4 与之相对应的是,我得到的ID列表如下所示: 1, 2, 3, 4

My below foreach is unfortunately only inserting the first ID of the array only.. 不幸的是,我下面的foreach仅插入数组的第一个ID。

foreach ($strFoo as $strFooName) {

        $strSql="INSERT INTO table (ID) 
                 VALUES ('$strBar')";
    }

How can I insert each ID into my table? 如何将每个ID插入表格?

It'd have to be: 必须是:

INSERT INTO table (ID) VALUES (1), (2), (3), (4)

so your processing step would need to be 因此您的处理步骤需要

$values = array();
foreach ($strFoo as $strFooName) {
     $values[] = '(' . intval($strFooName) . ')';
}

$strBar = implode(',', $values);

Note the addition of intval - that ensures that only valid numbers get inserted into the SQL statement. 请注意intval的添加-确保仅将有效数字插入到SQL语句中。 Your version was vulnerable to SQL injection attacks. 您的版本容易受到SQL注入攻击。

$strSql="INSERT INTO table (ID) VALUES ('$strBar')";

应该

$strSql="INSERT INTO table (ID) VALUES ('$strFooName')";

您使用$strFooName在数组中循环,但您插入的是$strBar ,上面刚刚更新了一次。.也许是问题所在

From 12.2.5. 12.2.5开始。 INSERT Syntax 插入语法

INSERT statements that use VALUES syntax can insert multiple rows. 使用VALUES语法的INSERT语句可以插入多行。 To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. 为此,请包括多个列值列表,每个列值括在括号内并用逗号分隔。 Example: 例:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9); 插入tbl_name(a,b,c)值(1,2,3),(4,5,6),(7,8,9);

That said, however. 话虽如此。 It looks like you're trying to just loop straight through your post array with this piece of code 看来您正在尝试使用这段代码直接循环遍历post数组

foreach ($strFoo as $strFooName) {
        $strSql="INSERT INTO table (ID) VALUES ('$strBar')";
}

$strBar in that example hasn't been created. 该示例中的$strBar尚未创建。 You might try 你可以试试

foreach ($strFoo as $strFooName) {
        $strSql="INSERT INTO table (ID) VALUES ('$strFooName')";
}

Although you should also look into preventing SQL injection if you're going to do that. 虽然您也应该考虑防止SQL注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM