如果还有PHP的话

时间:2016-10-18 03:15:22

标签: php if-statement

美好的一天。我的问题在这里: 我想显示结果,如果从SQL获得的计数大于0,如果计数为0,则结果将不会显示。 这里是我在php中添加if else语句后的当前输出:

    {"result":[]}

这是在我的php中添加if else语句之前的输出:

 { "result": [
    {"day":"1","count":"0"},
    {"day":"2","count":"2"},
    {"day":"3","count":"0"},
    {"day":"4","count":"0"}....

我希望结果只有tis:

    {"result":[
      {"day":"2","count":"2"}
    ]}

这是我的PHP代码:     

define('HOST','xx');
define('USER','xx');
define('PASS','xx');
define('DB','x');


//$month = $_POST['month'];
//$year = $_POST['year'];

$month = 10;
$year=2016;

$con = mysqli_connect(HOST,USER,PASS,DB);

$result = array();
 for ($day=1 ; $day<=31 ; $day++) {
     $sql = "select count(entryID) from Entry where
         EXTRACT(DAY FROM(entryTime)) = '$day'  AND
         EXTRACT(MONTH FROM(entryTime)) = '$month' AND 
         EXTRACT(YEAR FROM(entryTime))= '$year'";
     $res = mysqli_query($con,$sql);

if($row[0] >0)
     $day2 = (string)$day;
     while($row = mysqli_fetch_array($res)) {
         array_push($result,
         array('day' =>$day2,
            'count' => $row[0]
         ));

         }
}

 }


 echo $appear . json_encode(array("result"=>$result));



mysqli_close($con);

?>

1 个答案:

答案 0 :(得分:0)

  

您的条件检查区$row中的变量if($row[0] > 0) {尚未在使用它的位置定义。换一种说法;整个条件逻辑应该移动到while循环结构中...

也许,下面的代码片揭示了一些亮点:

<?php

    define('HOST','xx');
    define('USER','xx');
    define('PASS','xx');
    define('DB','x');


    $con    = mysqli_connect(HOST,USER,PASS,DB);
    $month  = 10;
    $year   = 2016;
    $result = array();
    /****************************|
    | $month  = $_POST['month']; |
    | $year   = $_POST['year'];  |
    |****************************/


    for($day=1; $day<=31; $day++) {
        $sql    = " SELECT COUNT(entryID) ";
        $sql   .= " FROM Entry WHERE ";
        $sql   .= " EXTRACT( DAY FROM(entryTime) )      = '$day'   ";
        $sql   .= " AND EXTRACT(MONTH FROM(entryTime))  = '$month' ";
        $sql   .= " AND EXTRACT(YEAR FROM(entryTime))   = '$year'  ";
        $res    = mysqli_query($con,$sql);  

        while($row = mysqli_fetch_array($res)) {
            if($row[0] > 0) {        //<== CONDITIONAL LOGIC HERE, INSTEAD
                $day2 = (string)$day;
                array_push($result,
                    array('day'     => $day2,
                          'count'   => $row[0]
                    )
                );
            }
        }
    }   

    //NOTICE: THE $appear VARIABLE IS NOT DEFINED IN YOUR CODE. 
    echo $appear . json_encode(array("result"=>$result));   
    mysqli_close($con);