检查数据库返回结果是否为PHP

时间:2015-12-03 21:27:58

标签: php sql pdo

我有具体问题:

if (isset($_POST['dateselected'])) {
                $selecteddate = $_POST['dateselected'];
                list($chosendate) = explode(' ', trim($selecteddate));
                $showdata = $db->prepare("SELECT * FROM adherence WHERE dateandtime= :chosendate AND lastname= :lastname");
                $showdata->bindParam(':chosendate', $chosendate);
                $showdata->bindParam(':lastname', $lastname);
                $showdata->execute();
                foreach ($showdata as $rowas){
                echo '<div class="twenty name">', $rowas["lastname"], $rowas["firstname"], '</div>';
}}

这是我的代码,如果没有脚本中要求的结果,如何打印出来的东西?假设数据库不包含这样的条件,如下所示:WHERE dateandtime= :chosendate AND lastname= :lastname如何检查返回的值,如果没有正确的结果返回,则打印出来的东西?

2 个答案:

答案 0 :(得分:2)

请尝试以下操作:

if (isset($_POST['dateselected'])) {
            $selecteddate = $_POST['dateselected'];
            list($chosendate) = explode(' ', trim($selecteddate));
            $showdata = $db->prepare("SELECT * FROM adherence WHERE dateandtime= :chosendate AND lastname= :lastname");
            $showdata->bindParam(':chosendate', $chosendate);
            $showdata->bindParam(':lastname', $lastname);
            $showdata->execute();
            if ($rowas= $showdata->fetch(PDO::FETCH_ASSOC)) {
                do {
                    //something with data
                    echo '<div class="twenty name">', $rowas["lastname"], $rowas["firstname"], '</div>';
                } while ($rowas= $showdata->fetch());
            } else {
                echo 'no data';
            }

答案 1 :(得分:0)

chris 85提到了rowcount,这是正确的方法。如果不存在,这将避免获取过程。它是最快的方法。此外,为了加速预处理绑定,最好指定它是什么数据类型(PDO :: PARAM_STR)。

if (isset($_POST['dateselected'])) {
            $selecteddate = $_POST['dateselected'];
            list($chosendate) = explode(' ', trim($selecteddate));
            $showdata = $db->prepare("SELECT * FROM adherence WHERE dateandtime= :chosendate AND lastname= :lastname");
            $showdata->bindParam(':chosendate', $chosendate,PDO::PARAM_STR);
            $showdata->bindParam(':lastname', $lastname,PDO::PARAM_STR);
            $showdata->execute();
            $count= $showdata->rowCount();
            if ($count !==0){
                $rowas= $showdata->fetch(PDO::FETCH_ASSOC)
                foreach ($showdata as $rowas){
                     echo '<div class="twenty name">', $rowas["lastname"], $rowas["firstname"], '</div>';
                }}
            }else {
            echo 'no data';
            }