0

我正在尝试从数据库中的费用表中返回三个参数。这是我的函数,位于 users.php

public function expense($username, $i) {
    $query = $this->db->prepare("SELECT * FROM `expenses` WHERE `username`= ?");
    $query->bindValue(1, $username);
    $i=1;
    $totalSpent=0;

    try{

        $query->execute();
        foreach ($query as $row) {
                    print "Username: " .  $row['username'] .", Amount: ". $row['amount'] ."$, Type: ". $row['type'] .", Date: ". $row['date'] .", Comment: ". $row['comment']   . ".<br>";
                    $totalSpent+=$row['amount'];
                    $i++;
                }

        return $query->fetch();
        return $i;
        return $totalSpent;

    } catch(PDOException $e){

        die($e->getMessage());
    }

}

我已经在我的 view.php 文件中设置了它来检索与用户名匹配的列,如下所示:

        <?php
    $users->expense($username);
    ?>

我的问题是我正在向函数发送一个参数 ( $username),但根据函数,我还想检索$i(实际上是行数)和 $totalSpent金额行的总数。

查看行工作正常,但我尝试了多种方式,但无法设法取回$iand$totalSpent变量。

我很新,所以如果我做错了,我期待有关如何使我的代码更好的建议。

4

1 回答 1

0

您只能从函数调用中返回一项,因此将该项设为数组或对象:

return array(
    'results' => $query->fetch(),
    'i' => $i,
    'totalSpent' => $totalSpent
);

访问使用:

$returnValues = $users->expense($username);
$userQueryResult = $returnValues['results'];

但是当您使用一个类时,您还可以使用这些值设置公共类属性,然后从方法外部访问对象属性

public function expense($username, $i) {
    $query = $this->db->prepare("SELECT * FROM `expenses` WHERE `username`= ?");
    $query->bindValue(1, $username);
    $i=1;
    $totalSpent=0;

    try{

        $query->execute();
        foreach ($query as $row) {
                    print "Username: " .  $row['username'] .", Amount: ". $row['amount'] ."$, Type: ". $row['type'] .", Date: ". $row['date'] .", Comment: ". $row['comment']   . ".<br>";
                    $totalSpent+=$row['amount'];
                    $i++;
                }

        $this->queryResult = $query->fetch();
        $this->i = $i;
        $this->totalSpent = $totalSpent;

    } catch(PDOException $e){

        die($e->getMessage());
    }

}

并使用

$users->expense($username);
$userQueryResult = $users->queryResult;

等等

后者将是一种更清洁的方法

于 2013-11-04T13:29:56.200 回答