我有一个函数,它检查一个查询,然后使用while循环来提取数据,我想返回这些数据,但我仍然希望它增加,但我读到返回终止一个函数,因此会使它无法增加。有没有解决的办法?
$this->messages = array();
while($row = $data) {
$this->messages[$i]['id'] = $row['id'];
$this->messages[$i]['title'] = $row['title'];
$this->messages[$i]['message'] = $row['message'];
$i++;
这个循环在函数内部,我想继续,直到循环完成,但是我不能返回任何值..是否有解决这个问题?
谢谢
编辑:
<?php
function Message($username){
$query = "SELECT * FROM msg WHERE `to` = '".$this->userid."' && `to_viewed` = '0' && `to_deleted` = '0' ORDER BY `created` DESC";
$stmt = $this->connection->prepare($query);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows = $stmt->fetchColumn();
if($num_rows) {
$i=0;
$this->messages = array();
while($row = $data) {
// want to return these 3 for each result
$this->messages[$i]['id'] = $row['id'];
$this->messages[$i]['title'] = $row['title'];
$this->messages[$i]['message'] = $row['message'];
$i++;
}
} else {
return 1;
}
}
?>
答案 0 :(得分:4)
使用PDO::fetchAll()
,它返回所有结果的数组,而不是一次返回一行:
function Message($username){
$query = "SELECT * FROM msg WHERE `to` = '".$this->userid."' && `to_viewed` = '0' && `to_deleted` = '0' ORDER BY `created` DESC";
$stmt = $this->connection->prepare($query);
$stmt->execute();
$this->messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $this->messages;
}
但要教你一些循环(一个CS 101概念 - 人们学习如何编程会发生什么?),这是你自己编写代码的方法:
$stmt->execute();
$this->messages = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
$this->messages[] = $row;
}
return $this->messages;