如果存在现有记录,则无法预先填充单选按钮

时间:2016-05-06 03:06:24

标签: php mysqli

这是一个简单的应用程序,带有3个问题的表单。每个问题都有2个选项。如果用户之前已提交过答案,那么该表单应该预先填充,但由于某种原因,它不是。

这是代码。非常感谢任何帮助或指导。

<?php

    $user_id = $_SESSION['user_id'];
    $anthem1 = '';
    $cointoss2 = '';
    $firstscore3 = ''; 

    if (isset($_POST['submit'])) {

        if (isset($_POST['anthem1'])) {

            $anthem1 = mysqli_real_escape_string($connection, $_POST['anthem1']);
        }       

        if (isset($_POST['cointoss2'])) {
             $cointoss2 = mysqli_real_escape_string($connection, $_POST['cointoss2']);
        }       

        if (isset($_POST['firstscore3'])) {
             $firstscore3 = mysqli_real_escape_string($connection, $_POST['firstscore3']);
        }


        $query = "INSERT INTO mypicks (user_id, anthem1, cointoss2, firstscore3) 
                      VALUES ('{$user_id}','{$anthem1}','{$cointoss2}','{$firstscore3}')
                      ON DUPLICATE KEY UPDATE anthem1 = '{$anthem1}',
                      cointoss2 = '{$cointoss2}',
                      firstscore3 = '{$firstscore3}'";


        $result = mysqli_query($connection, $query);
    }


    $query = "SELECT * FROM mypicks WHERE user_id = {$user_id}";
    $result = mysqli_query($connection, $query);
    if($result->num_rows == 1) {

        $user_picks = mysqli_fetch_row($result);
        $anthem1 = $user_picks['anthem1'];
        $cointoss2 = $user_picks['cointoss2'];
        $firstscore3 = $user_picks['firstscore3'];
    }

?>

这是表格(一个问题):

<form action="Game1_MyPicks.php" method="post">

Will the National Anthem be over 3 mins and 15 secs? <br />
Over  <input type="radio" name="anthem1" value="Over" <?php if ($anthem1=="Over") print('checked="checked"') ?>/><br />
Under <input type="radio" name="anthem1" value="Under" <?php if ($anthem1=="Under") print('checked="checked"') ?>/><br />

</form>

2 个答案:

答案 0 :(得分:0)

<input type="radio" name= "anthem1" value="" <?php if ($anthem1) echo "checked";?>>

答案 1 :(得分:0)

    <form action="Game1_MyPicks.php" method="post">

Will the National Anthem be over 3 mins and 15 secs? <br />
Over  <input type="radio" name="anthem1" value="Over" <?php if ($anthem1=="Over") print("checked"); ?>/><br />
Under <input type="radio" name="anthem1" value="Under" <?php if ($anthem1=="Under") print("checked"); ?>/><br />

</form>