如何使用PHP将数组插入到我的SQL表的单个字段中

时间:2018-03-03 20:16:49

标签: php html mysql

我有复选框条目,我按照html名称附加到列表中,如下所示:

    Choose no more than three categories:<br>
    <input id='category1' type="checkbox" name="boxsize[]" 
    onclick="CountChecks('listone',3,this)" value="asian">Asian
    <input id='category2' type="checkbox" name="boxsize[]" 
    onclick="CountChecks('listone',3,this)" value="asianFusion">Asian Fusion

我还有许多其他复选框。然后我通过这样做来破坏这个列表:

    $sanentry=implode(',',$_REQUEST["boxsize"]);

当我回复$ sanentry时,我会得到以下格式的所选值列表:asian,asian fusion。但是,当我尝试将这些值发送到mysql中的种族表时,种族列是空的。这是我用来将这些值发送到我的表的post方法和查询。

    $sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
    $sql3="INSERT INTO 
    ethnicity(restaurant_id,ethnicity)VALUES('$sanrestid','$sanethnicity')";
    if ($con->query($sql3) === TRUE) {
    echo "New record in ethnicity table created \n";
    } else {
    die("Error: " . $sql3 . "<br>" . $con->error);
    }
    mysqli_close($con);
    ?>

我的restaurant_id列没有问题,因为它正在更新,但是对于插入的每个新行,种族列总是空白。有谁知道我做错了什么? enter image description here

3 个答案:

答案 0 :(得分:1)

猜测变量名称是错误的。应该是$sanethnicity您的查询中有$ethnicitydb

$sql3="INSERT INTO ethnicity(restaurant_id,ethnicity) VALUES('$sanrestid','$sanethnicity')";

另外,这是具有原始伦理数组的字段吗? $_POST['$sanentry']或已被破坏。你可能想要这个:

$sanethnicity=mysqli_real_escape_string($con, $sanethnicity);

由于$sanethnicity之前已被破坏,如:

$sanethnicity = implode(',',$_REQUEST["boxsize"]);

答案 1 :(得分:0)

在这一行中你尝试使用$ sanentry作为$ _POST中的条目...

$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);

应该是

$sanethnicity=mysqli_real_escape_string($con, $sanentry);

虽然 - 你应该考虑使用预准备语句和绑定变量。

答案 2 :(得分:0)

如果要在不丢失数组结构的情况下存储它,则应使用serialize