将数据库内的值与输入值进行比较

时间:2015-03-28 16:07:07

标签: php sql forms if-statement

我的 if语句无法识别文本框名称(" ans")。我应该改变什么?我应该把它放在哪里?我也想知道我的if语句是否正确;我想比较数据库中的值与输入值(" ans")。提前致谢。

<?php
    $con = mysql_connect("localhost", "root", "avtt123");
    mysql_select_db("arvintarrega",$con);

    $sql = "SELECT * from identification";
    $myData = mysql_query($sql,$con);   

    echo '<form method = "POST">';

while($iden = mysql_fetch_array($myData))
{   
    echo '<center>' . $iden['question_number'] . '. ' . $iden['statement'] . ' <input type = "text" name = "ans"></input></center></br>';

    if($iden['correct_answer'] == $_REQUEST['ans'])
       {
        echo "Correct";
       }
    else
       {
        echo "Wrong";
       } 
}   
    echo '</form>';
?>
<form method = "POST">
<input type = "submit" name = "submit" value = "Submit" class="btn btn-warning">
</form> 

Here's my database

1 个答案:

答案 0 :(得分:2)

尝试以下内容对我有用,并且我正在使用mysqli_连接和查询,因此请使用您自己的凭据更改xxx

<?php
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$Link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($Link->connect_errno > 0) {
  die('Connection failed [' . $Link->connect_error . ']');
}

$sql = "SELECT * from identification LIMIT 1";

$myData = mysqli_query($Link, $sql);   

    echo '<form method = "POST">';

while($iden = mysqli_fetch_array($myData))
{
    echo '<center>' . $iden['question_number'] . '. ' . $iden['statement'] . ' <input type = "text" name = "ans"></center><br/>';

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

{

    if(isset($_POST['ans']) && $iden['correct_answer'] == $_POST['ans']){

      echo "Correct<br><br>";
       }
    else
       {
        echo "Wrong<br><br>";
       } 


    } // if(isset($_POST['submit'])) end brace

} // while loop end brace

echo '<input type = "submit" name = "submit" value = "Submit" class="btn btn-warning">';

     echo '</form>';
?>