如何将pdo返回的关联数组的内容放入数组中

时间:2015-12-14 07:12:04

标签: php mysql arrays pdo

我正在使用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的新手,非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

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;
  }

答案 1 :(得分:-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);

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

PDO :: FETCH_ASSOC 将返回按结果集中返回的列名索引的数组

成功时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