【问题标题】:How to get the contents of an associative array returned by pdo into an array如何将pdo返回的关联数组的内容放入数组中
【发布时间】:2016-03-19 14:35:34
【问题描述】:

我正在使用 PHO PDO 并让它返回一个关联数组。

我可以遍历 PDO 创建的关联数组,但我不知道如何从函数中返回数组。

function wantedrentals($provence, $country, $dbh)
   {
      echo "Now in wanted wanted rentals function<br><br>"; 

      $journeyrentalssarray = array();

      $sth = $dbh->query("SELECT summary, url, provence, country from tblAccomadation WHERE country = $country ");

    # setting the fetch mode
    $sth->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $sth->fetch()) 
        {
            echo $row['summary'] . "\n";
            echo $row['url'] . "\n";
            echo $row['provence'] . "\n";
            echo $row['country'] . "\n";
        }

  return $journeyrentalssarray;
  }

我对 PHP 和 PDO 非常陌生,希望能提供任何帮助。

【问题讨论】:

  • var_dump( $row ); 得到什么?
  • 你可能想看看这个:PDOStatement::fetchAll。此函数将整个结果作为数组返回。

标签: php mysql arrays pdo


【解决方案1】:
function wantedrentals($provence, $country, $dbh)
   {
      echo "Now in wanted wanted rentals function<br><br>"; 

      $journeyrentalssarray = array();

      $sth = $dbh->query("SELECT summary, url, provence, country from     tblAccomadation WHERE country = '$country' ");

    # setting the fetch mode
    $sth->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $sth->fetch()) 
        {
            $journeyrentalssarray[] = $row; // add $row to $journeyrentalssarray array
            echo $row['summary'] . "\n";
            echo $row['url'] . "\n";
            echo $row['provence'] . "\n";
            echo $row['country'] . "\n";
        }

  return $journeyrentalssarray;
  }

【讨论】:

  • 感谢您的反馈。如果发布的解决方案对您有用,您应该将其标记为“解决方案”,以奖励答案。
【解决方案2】:

你可能想要这样

function wantedrentals($provence, $country, $dbh)
   {
      echo "Now in wanted wanted rentals function<br><br>"; 

      $journeyrentalssarray = array();

      $sth = $dbh->query("SELECT summary, url, provence, country from tblAccomadation WHERE country = $country ");

    # setting the fetch mode
    //$sth->setFetchMode(PDO::FETCH_ASSOC);

    return $sth->fetch(PDO::FETCH_ASSOC);
  }

PDO::FETCH_ASSOC 将返回一个 array,按您的结果集中返回的列名进行索引。

成功时 fetch 函数的返回值取决于您的情况下的 fetch 类型,它的 FETCH_ASSOC 和 FALSE 在失败时返回。

更多信息请阅读here

我们还可以使用 fetchAll 来获取所有结果集行的数组。 所以函数可能看起来像这样。

function wantedrentals($provence, $country, $dbh)
       {
          echo "Now in wanted wanted rentals function<br><br>"; 

          $journeyrentalssarray = array();

          $sth = $dbh->query("SELECT summary, url, provence, country from tblAccomadation WHERE country = $country ");


        return $sth-> fetchAll(PDO::FETCH_ASSOC);
      }

更多信息请阅读here

【讨论】:

  • 这只会返回 1 行然后停止。
  • 对您有帮助吗? :D
猜你喜欢
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 2016-10-12
  • 2014-11-28
  • 2017-01-24
相关资源
最近更新 更多