最好的输出方式

时间:2016-08-19 22:50:20

标签: php

我试图运行php文件,但它给出了空变量,它在测验网站中用户回答我要将用户响应与数据库值进行比较但没有给出结果

这是调用函数的answer.php:

<?php
require("functions.php");

$ss=answer($_POST);

?>

这里是function.php文件

<?php
include('dbConnect.php');
?>

<?php

function answer($data){

    // creating query to get category id
    $sql="select * from category";
    $result=mysql_query($sql);
    while($row=mysql_fetch_array($result)){
        $cat=$row['cat_id'];
    }

    // another query to select table and compare values
    $response="select q_id, ans from questions where cat_id='$cat'" ;
    $right_answer=0;
    $wrong_answer=0;
    $unanswered=0;
    $result = mysql_query($response);

    while($qust=mysql_fetch_array($result)){

        if($qust['ans']==$_POST[$row['q_id']]){
            $right_answer++;
        } else if($_POST[$row['q_id']]=="no_attempt"){
            $unanswered++;
        } else {
            $wrong_answer++;
        }
   }
}
echo "right_answer : ". $right_answer."<br>";
echo "wrong_answer : ". $wrong_answer."<br>";
echo "unanswered : ". $unanswered."<br>";
?>

1 个答案:

答案 0 :(得分:1)

如果您明智地缩进代码,它有助于提高可读性,但更重要的是可调试性。

缩进时,您可以快速看到answer函数的最后3行超出函数范围并位于全局范围内。当你打电话给

require 'function.php` 
因此,它会立即运行最后3行,

echo "right_answer : ". $right_answer."<br>";
echo "wrong_answer : ". $wrong_answer."<br>";
echo "unanswered : ". $unanswered."<br>";

运行之前

$ss=answer($_POST);

因此在您实际创建3个变量并为其分配值之前。

像这样修改代码,它不会那样做

<?php
include('dbConnect.php');

function answer($data){

    // creating query to get category id
    $sql="select * from category";
    $result=mysql_query($sql);
    while($row=mysql_fetch_array($result)){
        $cat=$row['cat_id'];
    }

    // another query to select table and compare values
    $response="select q_id, ans from questions where cat_id='$cat'" ;
    $right_answer=0;
    $wrong_answer=0;
    $unanswered=0;
    $result = mysql_query($response);

    while($qust=mysql_fetch_array($result)){

        if($qust['ans']==$_POST[$row['q_id']]){
            $right_answer++;
        } else if($_POST[$row['q_id']]=="no_attempt"){
            $unanswered++;
        } else {
            $wrong_answer++;
        }
    }
    echo "right_answer : " . $right_answer."<br>";
    echo "wrong_answer : " . $wrong_answer."<br>";
    echo "unanswered : "   . $unanswered."<br>";
}
?>