我开始使用mysqli预处理语句并尝试编写一个类方法来检索符合特定日期条件的记录,但不显示它们 - 我希望能够在类之外格式化结果。
我在显示结果时使用类方法:
public function periodReceipts(){
global $db;
if($query = $db->prepare("SELECT * FROM receipts WHERE date BETWEEN ? AND ? ORDER BY date ASC")){
$query->bind_param("ss", $this->date1, $this->date2);
$query->execute();
$query->bind_result($id, $user_id, $vendor, $amount, $cat, $date);
$query->fetch();
while($query->fetch()){
echo "$id, $user_id, $vendor, $amount, $cat, $date <br/>";
}
$query->close();
}
}
我有一个类似的方法工作,执行mysqli查询,检索记录,计算总数,并返回该结果,未格式化,以便稍后显示:
public function runningTotal(){
global $db;
if($query = $db->prepare("SELECT amount FROM receipts WHERE user_id = ?")){
$query->bind_param("i", $this->uid);
$query->execute();
$query->bind_result($amount);
$running_total = 0;
while($query->fetch()){
$running_total += $amount;
}
$query->close();
}
return $running_total;
$db->close();
}
但我无法弄清楚如何让方法periodReceipts()表现得相似。我假设我需要将数据放入数组中,但是我该怎么做,以后如何访问它?
谢谢!
答案 0 :(得分:0)
更改您的方法,如下所示
...
$result = array();
while($query->fetch()){
$result[] = array(
'id' => $id,
'user_id' => $user_id,
'vendor' => $vendor,
'amount' => $amount,
'cat' => $cat,
'date' => $date
);
}
$query->close();
return $result;
...
然后你将获得你在阵列中的所有记录:
$result = $your_class_instance->periodReceipts();
var_dump($result);