php - 如何将 4 个单选按钮(每种颜色 4 种)存储到我的数据库中?

标签 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';
}
?> 

最佳答案

要获取值,您需要使用输入的 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'];

现在您需要将其插入到数据库中。您的数据库应该只保存选定的颜色。

You don't need columns like red, white, orange, green

You just need a column like 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);
}
....

关于php - 如何将 4 个单选按钮(每种颜色 4 种)存储到我的数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297978/

相关文章:

html - 如何检测横向模式并使用 css、查询或 js 隐藏 html 内容

HTML 结构 - 填充 2 个 float div 之间的空间

mysql - 用于持久保存 Google App Engine 上的 GWT 项目的外部 MySQL 数据库

php - 在 MYSQL PHP 中获取与 GROUP_CONCAT 相关的数据

php - onclick 禁用提交按钮

php - 使用复选框删除 Mysql 行

html - CSS - 断行而不断词

mysql - SQL 在列表 A 中选择但不在列表 B 中

php - 为 python 中的参数化查询生成变量长度放置持有符字符串

php - 在 PHP 中检测正确的字符编码?