如果使用PHP的SQL查询为空,则显示一条消息

时间:2018-10-19 09:15:35

标签: php html mysql

我正在尝试检查两个日期之间的sql表中的日期。如果查询结果为空,我试图显示一条消息。下面是我的代码

HTML:

<div class="result" id="result" name="result">
    <?php echo $head1; ?> <?php echo $out; ?> <?php echo $head2; ?> 
</div>  

<div class="result" id="result1" name="result1">
    <?php echo $out1; ?>
</div>

PHP代码:

if ($_POST['result_options'] == 'Data_Between_Dates'){  
    $startdate = $_POST['start_date'];
    $enddate = $_POST['end_date'];

    $sql ="Select date,select_bank,entry_type,income_cat,expense_cat,amount,expense_cat_sub 
           from wp_formdata 
           Where date BETWEEN  '$startdate' AND '$enddate' 
           order by date";

    $result = $conn -> query($sql);

    if($result>=1){
        $out = "";

        while($row = $result ->fetch_assoc()){
            $out .= "<tr><td>".$row["date"]."</td><td>".$row["select_bank"]."</td><td>".$row["entry_type"]."</td><td>".$row["income_cat"]."</td><td>".$row["expense_cat"]."</td><td>".$row["expense_cat_sub"]."</td><td>".$row["amount"]."</td></tr>";
        }
    }    
    else {
        $out1 = "No Result Found";
    }
}

我可以获取非空日期,但是以某种方式$out1 = "No Result Found";无法正常工作。这里有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以使用$result->num_rows检查查询是否返回了任何记录。它返回行数。

$result = $conn->query($sql);

if ($result->num_rows > 0) {

    $out = "";
    while ($row = $result->fetch_assoc()) {

        $out .= "<tr><td>" . $row["date"] . "</td><td>" . $row["select_bank"] . "</td><td>" . $row["entry_type"] . "</td><td>" . $row["income_cat"] . "</td><td>" . $row["expense_cat"] . "</td><td>" . $row["expense_cat_sub"] . "</td><td>" . $row["amount"] . "</td></tr>";

    }
} else {

    $out1 = "No Result Found";

}