未定义的偏移量:在 php 中为 0


Undefined offset: 0 in php

我用php编写了一个函数,它返回表中的所有值。 但是我的代码有问题。 当我在 else 中运行此函数时,它说错误"未定义的偏移量:0" 因此,如果有人对此有任何想法,请让我知道它是什么以及如何解决它谢谢

//Select All function
protected function selectAll($action, $tablename, $where = array()){
    try{
        $query = $this->_pdo->prepare("{$action} FROM {$tablename} WHERE {$where[0]} {$where[1]} ?");
        $query->bindValue(1, $where[2]);
        $query->execute();
        $result = $query->fetchAll(PDO::FETCH_OBJ);
        return $result[0];
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}

您应该添加一个检查以确保数组始终包含至少 2 $where个元素。还可以使用 fetch() 仅查询一行。

例:

$result = $query->fetch(PDO::FETCH_OBJ); // One result

您的解决方案:

protected function selectAll($action, $tablename, $where = array()){
  try{
    if( !count( $where ) < 2) {
      throw new PDOException( 'Invalid where filter' );
    }
    $query = $this->_pdo->prepare("{$action} FROM {$tablename} WHERE {$where[0]} {$where[1]} ?");
    $query->bindValue(1, $where[2]);
    $query->execute();
    // More than one result
    $result = $query->fetchAll(PDO::FETCH_OBJ);
    return $result;
  }
  catch(PDOException $e){
    echo $e->getMessage();
  }
}