dpqy77560 2013-07-24 11:46
浏览 49

PHP使用while循环来获取项目,使用动态选择功能?

Okay, I've never ever used dynamic functions, not sure why, I've never liked using explode(), implode(), etc.

but I've tried it out, and something went wrong.

    public function fetch($table, array $criteria = null)
    {
        // The query base
        $query = "SELECT * FROM $table";

        // Start checking
        if ($criteria) {
            $query .= ' WHERE ' . implode(' AND ', array_map(function($column) {
                return "$column = ?";
            }, array_keys($criteria)));
        }

        $check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
        $check->execute(array_values($criteria));

        $fetch = $check->fetch(PDO::FETCH_ASSOC);

        return $fetch;
    }

This is my query.

Basically I will return the variable $fetch which holds the fetch method.

and then somewhere, where I want to use the while loop to fetch data, I will use that:

$r = new Database();

while ($row = $r->fetch("argonite_servers", array("server_map" => "Wilderness")))
{
    echo $row['server_map'];
}

Now, I am not getting any errors, but the browser is loading and loading forever, and eventually will get stuck due to lack of memory.

That's because the loop is running and running without stopping. Why is it doing this? How can I get this dynamic query to work?

EDIT:

$r = new Database();
$q = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));

while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
    echo $row['server_map'];
}
  • 写回答

2条回答 默认 最新

  • duan3019 2013-07-24 11:59
    关注

    this is because you call your fetch function in a loop and it re-starts the query every time. You need to call the $check->fetch() in loop instead.

    or in other words, if your fetch function (which should probably have a different name) would return $check, then on the returned object you should call fetch() in a loop:

    $r = new Database();
    $q = $r->fetch(...);
    while($q->fetch()){...}
    

    you also need to edit your fetch function to end like this:

        $check->execute(array_values($criteria));
        return $check;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答