将多个复选框值插入单个列 - SQL数据库

时间:2014-05-22 01:57:33

标签: php checkbox

我希望从复选框中获取所有值并将其插入一列,如1,2,3

我的代码,我不知道出了什么问题

<form method="post" style="display:inline">
<label><input type="checkbox" name="data[]" value="1">1</label>
<label><input type="checkbox" name="data[]" value="2">2</label>
<label><input type="checkbox" name="data[]" value="3">3</label>
</form>

        <?php
if ($_POST['do'] =="insertawards")
{
    $media_array = $_POST['data'];
    $values = array();
    foreach($media_array as $value)
    {
        $values[] = $value;
    }
    $values = implode(',', $values);
        $db->query_write("INSERT INTO " . TABLE_PREFIX . " awards (awards_forumid,awards_userid,awards_name,awards_link) 
        VALUES('".$values."','0','".$_POST['awards_name']."','".$_POST['awards_link']."') ");
}
        ?>

当我使用implode时,我得到错误并在数据库上插入0

$media_array = $_POST['data'];
foreach ($media_array as $one_media)
{
$source .= $one_media;
}
$source = implode(',', $source);

2 个答案:

答案 0 :(得分:1)

无论如何,如果您需要正确地破坏值,我认为提交按钮丢失了。考虑这个例子:(我假设插入1,2,3,而不是像1,2,3那样插入整个字符串)

<?php

define('TABLE_PREFIX', 'vb_');

if(isset($_POST['submit'])) {
    // quick and dirty, just roll up your sanitation
    $media_array = $_POST['data'];
    $awards_name = '"'.$_POST['awards_name'].'"';
    $awards_link = '"'.$_POST['awards_link'].'"';
    $checkbox_values = '"'.implode(',', $media_array).'"';
    $statement = "INSERT INTO ".TABLE_PREFIX."awards (awards_forumid,awards_userid,awards_name,awards_link) ".
        "VALUES ($checkbox_values, '0', $awards_name, $awards_link)";
    echo $statement;
    // INSERT INTO vb_awards (awards_forumid,awards_userid,awards_name,awards_link) VALUES ("1,2,3", '0', "best_website", "http://www.google.com/")
}

?>

<form method="post" style="display:inline">
    <input type="hidden" name="awards_name" value="best_website" />
    <input type="hidden" name="awards_link" value="http://www.google.com/" />
    <label><input type="checkbox" name="data[]" value="1">1</label>
    <label><input type="checkbox" name="data[]" value="2">2</label>
    <label><input type="checkbox" name="data[]" value="3">3</label>
    <input type="submit" name="submit" value="submit" />
</form>

答案 1 :(得分:1)

我发现了什么问题,

问题不在代码中,这将在mysql上添加值数组,如1,2,3,4

$values = implode(',',$_POST['data'])."\n"; 

关于mysql字段类型的真正问题,我使它成为int(10)虽然必须是mediumtext甚至接受昏迷。

对不起,谢谢你的努力@ user1978142