如何将复选框中的值添加到数据库中

时间:2017-07-08 12:20:47

标签: php

让我首先说我搜索了这个并尝试了不同的东西,但我仍然卡住并需要一些帮助,因为这是我第一次尝试用php复选框... 我的HTML文件中有一个部分如下

<label class="labelStyle" for="text">XXX:</label>
                        <div class="checkboxAlign">
                            <input type="checkbox" name="XX[]" value="Apple">Apple<br>
                            <input type="checkbox" name="XX[]" value="Orange">Orange<br>
                            <input type="checkbox" name="XX[]" value="Strawberry">Strawberry<br>
                        </div>

但是我的PHP部分有问题,因为它没有将选中的项目添加到我的数据库中。

试试这个

if (!empty($_POST['XX']))
{
    foreach($_POST['XX'] as $check)
    {
        if(!($stmt = $mysqli->prepare("INSERT INTO table
            id = (
                SELECT id
                FROM yy
                WHERE xx = ?)"))){  
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
         if(!($stmt->bind_param("s",  $_POST['XX'])))    { 
        echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
    }

    }
}

我知道问题在这个php片段中,但我不确定我做错了什么。任何帮助,将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个

if (!empty($_POST['XX']))
{
    foreach($_POST['XX'] as $check)
    {
        if(!($stmt = $mysqli->prepare("INSERT INTO table
            id = (
                SELECT id
                FROM yy
                WHERE xx = ?)"))){  //added ? in place of $check
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
        if(!($stmt->bind_param("s", $check)))    { // added $check in place of $_POST['XX']
            echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
        }


    }
}

答案 1 :(得分:1)

更改

if(!($stmt->bind_param("s", $_POST['FoodTriggerItem'])))    {
                    echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
                }

if(!($stmt->bind_param("s", $check)))    {
                    echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
                }