php pdo搜索验证

时间:2015-02-12 12:24:33

标签: php pdo

这是我的搜索代码

如果用户输入的值不存在,我需要验证这一点,然后显示消息数据不可用。

如果用户输入不可用,我需要验证代码来回显未找到数据的消息。

我的意思是,如果找到了值,则显示未显示的消息。

我尝试下面的代码但是这个回显数据和消息也是。

 <?php
    if($_POST && isset($_POST['submit']))
    {                       
        $result=$db->prepare('SELECT scheme_name,city,coupon,amount,receipt_no,book_no2 FROM scheme_master WHERE receipt_no=:receipt_no');
        $result->bindParam(':receipt_no',$_POST['receipt_no']);
        $result->execute(); 
        $data = $result->fetchAll();
        $coupons = array(); 
            foreach($data as $row)
            {    
                $scheme =  $row['scheme_name'];
                $book =  $row['book_no2'];
                $coupons[] = $row['coupon']; 
                $cit =  $row['city'];
                $amou =  $row['amount'];
                $rec =  $row['receipt_no']; 
            } 
if(!strlen($result) >0 || $result==0)
    {   
        $errors['Message']= "Data Not Found";
    }

    }
    ?>

1 个答案:

答案 0 :(得分:0)

PDO::fetchAll将返回一组记录;如果没有找到记录,则表示空数组。您可以使用count/sizeof

检查数组是否为空
<?php
if ($_POST && isset($_POST['submit'])) {
    $result = $db->prepare('SELECT scheme_name,city,coupon,amount,receipt_no,book_no2 FROM scheme_master WHERE receipt_no=:receipt_no');
    $result->bindParam(':receipt_no', $_POST['receipt_no']);
    $result->execute();
    $data    = $result->fetchAll();
    $coupons = array();

    if (count($data) == 0) {
        $errors['Message'] = "There are no results";
    } else {
        foreach ($data as $row) {
            $scheme    = $row['scheme_name'];
            $book      = $row['book_no2'];
            $coupons[] = $row['coupon'];
            $cit       = $row['city'];
            $amou      = $row['amount'];
            $rec       = $row['receipt_no'];
        }
    }
}
?>