【问题标题】:mysqli array fetching is not getting datamysqli数组获取未获取数据
【发布时间】:2018-02-01 23:29:49
【问题描述】:

我必须在单行中获取结果,但我不能运行多行。我怎样才能解决这个问题?

$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
 $result = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
 $stmt->close();
 return $result;
 }

我得到了像这样明智的结果

{"ID":2,"Name":"Anju"}

但我需要获取所有用户结果。我的代码在这里

$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = array();
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row;
}
 $stmt->close();
 return $result;
}

我收到了错误

致命错误:在第 5 行对非对象调用成员函数 fetch_array()

该行是:

while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC))  

我的预期结果是

 {"ID":1,"Name":"Obi"}, {"ID":3,"Name":"Oman"}, {"ID":4,"Name":"Anju"}

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    $stmt = $this->conn->prepare("SELECT * from user where id=?");
    $stmt->bindValue(1, $id);

    试试这个方法

    并尝试 fetchAll 而不是 fetch_array

    【讨论】:

    • 我试试我得到了像Warning: mysqli_stmt::bind_param(): Undefined fieldtype 1 (parameter 2) 这样的错误。
    • 您尝试过 bindValue 吗?从您的错误中,我看到您仍在使用 bind_param()
    【解决方案2】:

    您可以进行以下更正。

    改变

    $rows->fetch_assoc(MYSQLI_ASSOC)
    

    $rows->fetch_assoc()
    

    应该是这样的

    if ($stmt->execute()) {
        $rows = $stmt->get_result();
        $result = array();
        while ($row = $rows->fetch_assoc()){
            $result[] = $row;
        }
        $stmt->close();
        return $result;
    } else {
        return NULL;
    }
    

    建议:始终在SELECT 中指定列列表,这样可以加快查询执行速度。

    请阅读php manual

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 1970-01-01
      • 2015-12-16
      • 2012-08-21
      • 2021-09-10
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2017-12-06
      相关资源
      最近更新 更多