【问题标题】:Notice: Undefined variable: row when PDO returns no data注意:未定义变量:PDO 没有返回数据时的行
【发布时间】:2014-04-28 05:27:20
【问题描述】:

我有这个代码 -

$previous_date = date('Y-m-d',strtotime("-14 days"));

$conn = testdb_connect ();

        $getfamilydate= get_family_date ($previous_date);

        if (! $row)
        {
        echo "No testcase being executed in the selected duration";
        } else { while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
            { 
            foreach($row as $key) 
                {
                    $twoWeekfamily[] = $key;
                }           
            }
        }

我在这里尝试检查查询是否返回指定持续时间(上一个日期)的任何结果,如果没有,它应该显示消息,否则返回数组。

我的持续时间像 -

1day, 2ay, 1week, 2 week.. 等等,我在所有持续时间内都使用相同的代码。此逻辑在 1 天内可以正常工作,即,如果没有数据显示 msg,但对于所有其他逻辑,如果查询返回没有数据而不是抛出 Undefined variable: row notice。

这里的逻辑有什么问题?

【问题讨论】:

  • 您正在测试尚未设置的内容:` if (!$row)`

标签: php


【解决方案1】:

做一些类似的事情 -

while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
        { 
        foreach($row as $key) 
            {
                $twoWeekfamily[] = $key;
            }           
        }
 if(empty( $twoWeekfamily))
 {
echo "No testcase being executed in the selected duration";
 }

【讨论】:

    【解决方案2】:

    如下修改你的代码

    if (! $getfamilydate){
        echo "No testcase being executed in the selected duration";
    }
    else {
         $count = $getfamilydate->rowCount();
         if($count > 0){
             while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
             { 
    
                  var_dump($row);
    
             }
         }
        else{
            echo "No rows found";
        }
    }
    

    在您的代码中,您在将值设置为 $row 之前检查 $row

    【讨论】:

    • 在这种情况下不打印任何味精!
    • 尝试在 else 中放置一个 echo 以检查它是否到达 else。以及为什么在 while 内使用 foreach 。检查我的新更新。
    • 我正在使用 foreach 将输出保存在数组中。
    • 试试我的更新来检查你的天气,你会先到里面。然后尝试把你的 for 循环
    • 它在 else 部分但没有显示任何输出。
    【解决方案3】:
    if (!$getfamilydate->rowCount()){
        echo "No testcase being executed in the selected duration";
    }else { while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
            { 
                foreach($row as $key) 
                {
                    $twoWeekfamily[] = $key;
                }           
            }}
    

    if 语句中使用$getfamilydate->rowCount() 而不是$row

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 1970-01-01
      • 2012-09-24
      • 2020-08-21
      • 1970-01-01
      • 2021-03-07
      相关资源
      最近更新 更多