简体   繁体   English

PHP PDO FetchAll 与 Fetch

[英]PHP PDO FetchAll vs Fetch

I believe I am using the PDO fetch functions completely wrong.我相信我完全错误地使用了 PDO 获取功能。 Here is what I am trying to do:这是我想要做的:

Query a row, get the results, use a helper function to process the results into an array.查询一行,获取结果,使用辅助函数将结果处理成数组。

Query询问

function userName($db){
  $q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
  $q->bindParam(":user", $user);
  $q->execute();
  $qr = $q->fetchAll(PDO::FETCH_ASSOC);
  if ($qr->rowCount() > 0){
    foreach($qr as $row){
      $names[$row['id']] = buildArray($row);
    }
  return $names;
  }
}

My custom array building function我的自定义数组构建函数

function buildArray($row){
 $usernames = array();
 if(isset($row['id'])) $usernames['id'] = $row['id'];
 if(isset($row['name'])) $usernames['name'] = $row['name'];
}

I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once.我实际上从中得到了我想要的东西,但是当我在两者之间回声时,我看到事情循环了 3 次而不是一次。 I think I am misusing fetchAll.我想我在滥用 fetchAll。

Any help appreciated任何帮助表示赞赏

If you're going to build a new array, there's not much point in having fetchAll() build an array.如果您要构建一个新数组,那么让fetchAll()构建一个数组没有多大意义。 Write your own fetch() loop:编写自己的fetch()循环:

function userName($db){
    $q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
    $q->bindParam(":user", $user);
    $q->execute();
    $names = array();
    while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
        $names[$row['id']] = $row;
    }
    return $names;
}

There's also no need for buildArray() , since $row is already the associative array you want.也不需要buildArray() ,因为$row已经是您想要的关联数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM