[英]OOP PDO fetch while loop
I have a function in my class which is not completed. 我的课程中有一个功能尚未完成。 I'm searching a way to do it all night long. 我正在寻找一种整夜做的方法。 Well I want to fetch all the result of a SELECT request to MYSQL using PDO in a OOP class/function. 好吧,我想在OOP类/函数中使用PDO将所有SELECT请求的结果提取到MYSQL。
Here my function 在这里我的功能
function select($query)
{
try
{
$sql = $this->connect->query($query);
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
return ????
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
I know that I can do it with a while loop, I tested a few options but most of the time I only got 1 result. 我知道我可以用while循环来做,我测试了一些选项,但大多数时候我只得到1个结果。 Anyone a point for me, where I could start my search for a solution to this issue? 对我来说,有什么意义,我可以开始寻找这个问题的解决方案吗?
It's pretty easy, actually. 实际上,这很简单。 You use PDO::FETCH_CLASS
and specify which class you want to instantiate for each row. 您使用PDO::FETCH_CLASS
并指定要为每行实例化的类。
Here is an example that fetches all available rows as an array of objects of class YourClassName
. 下面是一个示例,它将所有可用行作为类YourClassName
的对象数组获取。
function select($query) {
try {
$sql = $this->connect->query($query);
return $sql->fetchAll(PDO::FETCH_CLASS, YourClassName);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
Only use $sql->fetch(PDO::FETCH_ASSOC)
within the while loop, not before, as you have it. 只在while循环中使用$sql->fetch(PDO::FETCH_ASSOC)
,而不是之前,就像你拥有它一样。
So, like: 所以,像:
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.