如何将四个每种颜色的4个单选按钮存储到数据库中?

时间:2019-01-21 21:26:39

标签: php html mysql mysqli

我有4个单选按钮,当用户选择一个具有在表单元格中显示的颜色的单选按钮时,它们每个都有1种颜色。当用户单击“提交”时,它将信息保存到我的数据库中,因此当用户返回网站时,他们可以有完全相同的选项。

我只是删除了数据库连接的详细信息。

我不知道自己做错了什么。

$first = $_POST['white'];
$first = $_POST['red'];
$first = $_POST['orange'];
$first = $_POST['green'];

$sql = "INSERT INTO savecolor (white, red, orange, green) VALUES ('$first')";

我可能把这些弄乱了。我真的不知道。^^

<form action="include/dbh.inc.php" method="post">
<table id="table">
    <tr>
            <td>
                <div class="white">
                    <input type="radio" name="first" value="white" onclick="setBgColor(this)" checked>
                    </div>
                <div class="red">
                    <input type="radio" name="first" value="red" onclick="setBgColor(this)">
                    </div>
                <div class="orange">
                    <input type="radio" name="first" value="orange" onclick="setBgColor(this)">
                </div>
                <div class="green">
                    <input type="radio" name="first" value="green" onclick="setBgColor(this)"> 
                </div>
            <br>
            This is a text.
</td>

php代码

<?php

$dbServername = "";
$dbUsername = "";
$dbPassword = "";
$dbName = "";

   $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

if(!$conn){
echo 'Not Connected To Server';
}

$first = $_POST['white'];
$first = $_POST['red'];
$first = $_POST['orange'];
$first = $_POST['green'];

$sql = "INSERT INTO savecolor (white, red, orange, green) VALUES('$first')";

if(!mysqli_query($conn,$sql))
{
echo 'Not Inserted';
}
else
{
 echo 'Inserted';
}
?> 

2 个答案:

答案 0 :(得分:1)

要获取值,您需要使用输入的name属性。

为了安全起见,您应该使用mysqli_real_escape_string。 mysqli_real_escape_string

$first = mysqli_real_escape_string($conn, $_POST['first']);

//Not $first = $_POST['first']
//Or not $first = $_POST['white'];

现在,您需要将此插入到数据库中。您的数据库应仅保留选择的颜色。

  

您不需要像红色,白色,橙色,绿色这样的列

     

您只需要一列诸如user_color

重建数据库后,我们将其插入。

$query = mysqli_query($conn, "INSERT INTO savecolor (user_color) VALUES ('$first')");
//Check it
if ($query) {
   echo 'Inserted';
} else {
   echo 'Not Inserted';
}

注意:

您应该先检查发布内容。

<?php
if (empty($_POST)) {
    //There is no post so exit.
    exit(0);
}
....

答案 1 :(得分:0)

请注意注释中的“ SQL注入”警告。学习如何使用准备好的语句并养成习惯。

在查询$sql = "INSERT INTO savecolor (white, red, orange, green) VALUES('$first')";中,它试图填充4列,但仅提供一个值。

您可能会考虑将savecolor表的布局更改为仅包含一个变量colorchoice或类似的变量。然后,您只需要在该表中插入$_POST['first'](在将查询更改为使用准备好的语句之后:)。