gpt4 book ai didi

PHP : PDO fetch() not showing result

转载 作者:行者123 更新时间:2023-11-29 07:05:02 25 4
gpt4 key购买 nike

我现在正在学习 PDO,我刚刚按照 Youtube 上的教程进行操作。所以在这里我有一个来自 Db 类的方法,我添加了一个新行 PDO::FETCH_ASSOC 因为我想尝试除了 foreach 之外的 while 循环。

public function query($sql, $params = array()){
$this->_error = false;
$this->_count = 0;
if($this->_query = $this->_pdo->prepare($sql)){

#check if theres a parameter and bindvalue to sql statement
if(count($params)){
$x = 1;
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}

#execute with or without parameter
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_whileFetch = $this->_query->fetch(PDO::FETCH_ASSOC);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
return $this;
}
} #end of GET function


public function whileFetch(){
return $this->_whileFetch;
}

foreach 运行良好,但我想尝试 while 循环,但它似乎不起作用,没有显示任何数据。

$query = $db->query("SELECT * from master_data.store");
while($row = $query->whileFetch()){
echo $row['name'];
}

我也尝试过这个,但出现错误。

while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row['name'];
}

最佳答案

问题是由于此方法调用 ->fetchAll(PDO::FETCH_OBJ) 造成的。由于您将从结果集中获取所有行作为数组并将其分配给实例变量 $results,因此此语句 $this->_whileFetch = $this->_query-> fetch(PDO::FETCH_ASSOC); 之后将不起作用。这就是为什么您将 $this->_whileFetch 设置为 false

所以解决方案是,

  • 从您的类中删除实例变量 $_whileFetch,您将不再需要它。
  • 从此 if($this->_query->execute()){ ... } block 中删除以下两行,

    $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
    $this->_whileFetch = $this->_query->fetch(PDO::FETCH_ASSOC);
  • whileFetch()方法中,而不是$this->_whileFetch,直接从结果集中获取下一行并返回,

    return $this->_query->fetch(PDO::FETCH_ASSOC);

因此,您的 query()whileFetch() 方法将如下所示:

public function query($sql, $params = array()){
$this->_error = false;
$this->_count = 0;
if($this->_query = $this->_pdo->prepare($sql)){
#check if theres a parameter and bindvalue to sql statement
if(count($params)){
$x = 1;
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}

#execute with or without parameter
if($this->_query->execute()){
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
return $this;
}
}

public function whileFetch(){
return $this->_query->fetch(PDO::FETCH_ASSOC);
}

稍后,您可以像这样进行查询和 while() 循环:

$query = $db->query("SELECT * from master_data.store");
while($row = $query->whileFetch()){
echo $row['name'];
}

关于PHP : PDO fetch() not showing result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42051321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com