取html单选按钮按钮的结果,并通过PHP将其放入mysql数据库

时间:2016-04-04 10:24:47

标签: php html mysql

我正在尝试创建一个动态网页,其中有4个单选按钮,如下所示: 你想睡觉吗 ?是否(作为按钮)和提交按钮。 你想吃东西吗 ?是否(作为按钮)和提交按钮。

然后我想把响应放到mysql数据库中。这是我的PHP代码:

<html>
<head>
<meta http-equiv="refresh" content="30">
<meta charset="UTF-8">
</head>
<body>
<form method="post" action="action_page.php">
 <label class="heading"> do you want to eat ?<label/>
  <input type="radio" name="radio" value="yes_1" checked> yes
  <input type="radio" name="radio" value="no_1"> No
  <input type="submit">
</form> 
<br>
<br>
<?php
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'root';
$password = '1234';
$dbh = new PDO($dsn, $username, $password);
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
{
echo "<span>You have selected :<b> ".$_POST['radio']."</b></span>";
}
else{ echo "<span>Please choose any radio button.</span>";}
}

?>
<form action="action_page.php">
  <label> do you want to sleep ?<label/>
  <input type="radio" name="radio" value="yes_2" checked> Oui
  <input type="radio" name="radio" value="no_2"> Non
  <input type="submit" name="submit" value="confirmer" />
</form>
<form action="iotpage.php">

<?php   
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'root';
$password = '1234';

$dbh = new PDO($dsn, $username, $password);
//if(isset($_POST['submit']))
//{
//foreach ($_POST['radio'] as $select2)
//{
//echo "You have selected for hum:" .$select2; // Displaying Selected Value
//}
//}
?>
</body>
</html>

我在我的sql db named action中创建了一个表,它包含第一个问题的第2列和第二个问题的第二列。如何修改我的代码以插入我的数据库。

1 个答案:

答案 0 :(得分:0)

将带有收音机的表格放入html

    <form action="action_page.php" method="post">
        <fieldset>
        <label class="heading"> Do you want to eat ?<label/>
            <legend>Options:</legend>
            Option One   <input type="radio" name="eat" value="yes"/>
            Option Two   <input type="radio" name="eat" value="no"/>
            <input type="submit" value="Save" />
        </fieldset>

        <fieldset>
        <label> Do you want to sleep ?<label/>
            <legend>Options:</legend>
            Option One   <input type="radio" name="sleep" value="yes"/>
            Option Two   <input type="radio" name="sleep" value="no"/>
            <input type="submit" value="Save" />
        </fieldset>
    </form>

在你的PHP方面(如果你使用php)获取post值,构造你的语句并执行它:

$eat = $_POST["eat"];
$statement = "INSERT INTO MyTable(option_name) VALUES($eat) ";

$sleep = $_POST["sleep"];
$statement = "INSERT INTO MyTable(option_name) VALUES($sleep) ";

显然,这是为了说明如果你想创建一个好的代码,你需要做更多的原则。