在函数中返回数据然后使用变量?

时间:2015-07-28 06:30:35

标签: php

我正在尝试使用一种经过修改的数据库类创建一个名为df1 <- structure(list(grp = c("AK", "AK", "TX", "TX", "TX")), .Names = "grp", class = "data.frame", row.names = c(NA, -5L)) 的函数。我可以从中获取信息,它可以工作,但这只是在函数中。这是代码:

query_select

这样就显示了这个:

public function query_select($query)
{
    try
    {
        $this->query = $this->pdo->prepare($query);
        $this->success = $this->query->execute();
        $result = $this->query->fetchAll();
        foreach($result as $row)
        {
            echo $row['id'], '<br>', $row['username'], '<br>', $row['password'];
        }
    }
    catch(PDOException $ex)
    {
        die($ex->getMessage());
    }
    $this->parameters = array();
}

我正在尝试这样做:

1
JoelE
123456

然后在我的页面文件中调用该函数后尝试这样的事情:

public function query_select($query)
{
    try
    {
        $this->query = $this->pdo->prepare($query);
        $this->success = $this->query->execute();
        $result = $this->query->fetchAll();
        return $result;
    }
    catch(PDOException $ex)
    {
        die($ex->getMessage());
    }
    $this->parameters = array();
}

但我明白了:

foreach($result as $row)
{
    echo $row['id'], '<br>', $row['username'], '<br>', $row['password'];
}

1 个答案:

答案 0 :(得分:3)

您需要先将函数返回的值赋给变量:

$result = query_select(...);
foreach($result as $row) {
  echo $row['id'], '<br>', $row['username'], '<br>', $row['password'];
}