gpt4 book ai didi

php - dbconnection 类 PGSQL 重写函数

转载 作者:行者123 更新时间:2023-11-29 14:36:20 25 4
gpt4 key购买 nike

我目前正在使用 pgsql 在 PHP 中编写一个 dbconnection 类。我已经编写了连接和查询函数,但我想知道如何获取结果。

目前我们需要使用这个函数来获取查询后的结果:

$db = new dbconnection();
$stmt= $db -> query("SELECT * FROM users");
pg_fetch_all($stmt);

为了获得更清晰的代码,我想执行以下操作来获取结果:

$db = new dbconnection();
$stmt= $db -> query("SELECT * FROM users");
$result = $stmt -> fetchAll();

对如何做到这一点有什么帮助吗?

提前致谢

最佳答案

dbconnectionquery 方法应该像这样返回一个Statement 的实例(PHP7,简化):

final class Statement
{
private $result;

public function __construct(array $result = [])
{
$this->result = $result;
}

public function fetch()
{
return $this->result[0];
}

public function fetchAll()
{
return $this->result;
}
}

所以你这样调用它(简化):

final class DBConnection
{
// constructor etc.

public function query(string $query)
{
// $result = result of the passed executed string $query

return new Statement($result);
}

}

关于php - dbconnection 类 PGSQL 重写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44109601/

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