Reputation: 21
I have a function, which checks a query, and then uses a while loop to extract data, I would like to return this data but I still want it to increment, but I read that return terminates a function, and thus would make it unable to increment. Is there a way around this?
$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++;
This loop is inside the function, I want to continue until the loop is done, but then I can't return any values.. is there a work around this?
Thank you
EDIT:
<?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;
}
}
?>
Upvotes: 1
Views: 4578
Reputation: 780994
Use PDO::fetchAll()
, it returns an array of all the results, rather than returning one row at a time:
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;
}
But to teach you about loops (a CS 101 concept -- what ever happened to people learning how to program?), here's how you would code it yourself:
$stmt->execute();
$this->messages = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
$this->messages[] = $row;
}
return $this->messages;
Upvotes: 4