【问题标题】:Checked values not inserting to DB - PHP检查值未插入数据库 - PHP
【发布时间】:2023-04-01 01:15:01
【问题描述】:

所以我试图从复选框中插入选中的值,但不起作用。我相信我的问题是它们一开始没有正确设置。我试图使用循环,但我相信我做错了:P

我的“isset”:

if(!empty($_POST))
{

    if(empty($_POST['name'])) {die("Please enter a Your Name.");}
    if(empty($_POST['ckboxes[]'])) {die("Please check at least one box.");}
    if(empty($_POST['ddown'])) {die("Please select a value.");}
    if(empty($_POST['txtDate'])) {die("Please type in a date.");}
    if(empty($_POST['agdis'])) {die("Please agree or disagree.");}
    if(empty($_POST['yn'])) {die("Please select Yes or No.");}

和插入过程:

//Insert for Checkboxes//
    /////////////////////////
    $query2 = "
        INSERT INTO coffee_ckbx (
            white,
            green,
            red,
            blue
        ) VALUES (
            :white,
            :green,
            :red,
            :blue   
        )
    ";

    foreach($_POST['ckboxes'] as $check){array($check);}

    $query_params2 = array(
        ':white' => $check['1'],
        ':green' => $check['2'],
        ':red' => $check['4'],
        ':blue' => $check['5']
    );

    try
    {
        // Execute the query to create the user
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);

        $stmt2 = $db->prepare($query2);
        $result2 = $stmt2->execute($query_params2);
    }
    //kept the catch out and other code due to lengthiness.

这是我的html:

            <li>
            <label for='ck-boxes'>Select from the check boxes: </label>
            <input type="hidden" name="ckboxes" value="0" />
            <input type='checkbox' id='' name='ckboxes' value='white'/>
            <input type='checkbox' id='' name='ckboxes' value='green'/>
            <input type='checkbox' id='' name='ckboxes' value='red'/>
            <input type='checkbox' id='' name='ckboxes' value='blue'/>
        </li>

有什么想法吗? 提前谢谢你:)

【问题讨论】:

    标签: php checkbox insert key-value isset


    【解决方案1】:

    尝试将[] 添加到名称的末尾,这样会告诉PHP 这是一个数组。

    <input type="hidden" name="ckboxes[]" value="0" />
    <input type='checkbox' id='' name='ckboxes[]' value='white'/>
    <input type='checkbox' id='' name='ckboxes[]' value='green'/>
    <input type='checkbox' id='' name='ckboxes[]' value='red'/>
    <input type='checkbox' id='' name='ckboxes[]' value='blue'/>
    

    同样不要引用数字,引号内的东西被视为string

    所以$check['1'] 应该是$check[1] 作为例子。

    【讨论】:

    • 实际输入的是form吗?
    • 是的,它们在表格中。在这里你可以看到我的代码,也许这会有所帮助。 codepad.org/2sL3slm6
    • 它对我来说非常好用。只需删除 isset($ckboxes) 并将 $ckboxes = $_POST['ckboxes']; 放入“isset”即可。
    • 感谢它现在正在工作。虽然我不明白你的意思,所以如果我使用相同的代码就不会。我的代码:codepad.org/FaltNYjI
    • 我确实有另一个我无法解决的问题。为了插入任何数据,我必须选中所有复选框,如果我没有选中那些我没有选中的复选框,则会出现“未定义的偏移量”错误。
    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 2017-05-08
    相关资源
    最近更新 更多