致命错误:在第 16 行的 C:xampphtdocsstudysite est.php 中调用布尔值上


Fatal error: Call to a member function fetchAll() on boolean in C:xampphtdocsstudysite est.php on line 16

我正在尝试在我的数据库中创建列,但是当我运行代码时,我得到

致命错误:在第 16 行的布尔值上调用成员函数 fetchAll()

$con = connect(DNS,USERNAME,PASSWORD);
//columns as arrays that i need to create if it doesn't exist
$columnname = array("urine_re","lab_investigation","a_records","crazy_gus");
$table='anc_hsd';
//function to check if column name exist if not create it
function columnExist($item,$table,$column){
  $exists = false;
  $sql = "SHOW COLUMNS FROM  $table";
  $result = $item->query($sql);
  $results=$result->fetchAll(PDO::FETCH_COLUMN);

  if(in_array($column,$results)){
    $exists=true ;
  }
  if(!$exists){
    $sql="ALTER TABLE $table ADD $column  INT(30) NULL";
    $item->exec($sql);
  }
}

//this is where I use the function
foreach($columnname as $key=>$value){
  columnExist($con, $table, $value);
}

如果查询失败,query() 方法可以返回 false。在处理它们之前检查是否有任何结果是一个好习惯:

 $result = $item->query($sql);
 if ($result) {
     $results=$result->fetchAll(PDO::FETCH_COLUMN);
 }
 else {
      // Handle errors
 }

但这只是错误处理,查询仍然失败。这很可能是因为 COLUMNS 不是数据库表中列的名称。

查询失败,返回 FALSE。然后你在布尔值中应用 fetchAll(),这是不可能的。在使用资源$result之前检查此查询的结果。

如果你想成为一名优秀的程序员,不要天真。永远不要假设你的函数调用、查询和类似的东西会起作用。始终考虑它们会失败的可能性并以某种方式进行检查。

在这种情况下,您应该具有以下保护:

$sql = "SHOW COLUMNS FROM  $table";
$result = $item->query($sql);
if ($result !== FALSE) {
    $results=$result->fetchAll(PDO::FETCH_COLUMN);
} else {
    // Alternative code telling what to do when the query fails
}

希望这有帮助!