无法弄清PDO TRY代码上的错误

时间:2018-01-22 04:34:15

标签: php pdo try-catch fetch

下面这段代码给了我这个错误

  

"致命错误:在布尔值"上调用成员函数setFetchMode()上   第21行

setFetchMode的行。

任何人都知道问题可能是什么?我无法解决这个问题:(

代码:

 try {
 $query = $dbh->query("SELECT name, city FROM schools WHERE 1 GROUP BY name, 
 city");
 $query->setFetchMode(PDO::FETCH_ASSOC);   //THIS IS LINE 21 error refers to
 $iterator = new IteratorIterator($query);
 foreach ($iterator as $row) {
 if (empty($row['name']) == false && !in_array($row['name'], $name_list))
        $name_list[] = $row['name'];
    if (empty($row['city']) == false && !in_array($row['city'], $city_list))
        $city_list[] = $row['city'];
 }

1 个答案:

答案 0 :(得分:0)

尝试执行此代码以查看PDO中的错误,之后您可以评估要修改的部分

$sql = "SELECT name, city FROM schools WHERE 1 GROUP BY name, 
city";
try {
   $stmt = $dbh->query($sql);
   $result = $stmt->setFetchMode(PDO::FETCH_NUM);
     while ($row = $stmt->fetch()) {
        print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
     }
 }
 catch (PDOException $e) {
    print $e->getMessage();
  }

如果此代码失败,它将为您提供错误