Reputation: 9037
Im using this code to retrieve all records associated with the usertype="user" row from mysql
class user{
public function getnews(){
$sql5 = "SELECT * FROM news WHERE usertype = 'user'";
$result = mysqli_query($this->db,$sql5);
$data = '';
while($row = mysqli_fetch_assoc($result)){
$data = '<article>';
$data .= '<h3>' . $row['title'] . '</h3>';
$data .= '<p>' . $row['content'] . '</p>';
$data .= '<footer>By: ' . $row['whoposted'] . ' / ' . $row['dateposted'] . '</footer>';
$data .= '</article>';
}
echo $data;
}
}
and then display the records with.
$user = new user();
$user->getnews()
and the structure of my database is.
id, title, content, whoposted, dateposted, usertype.
and assume i have one records that have usertype="admin"
id=autoincrement, title="this is the title", content="this is the content", dateposted="2015/03/08", usertype="admin"
and 5 records that have usertype="user"
id=autoincrement, title="this is the title", content="this is the content", dateposted="2015/03/08", usertype="user"
now, as you can see from my mysql query, i suppose to get all the records that has usertype="user" and it suppose to display all records except for one record which has usertype="admin" but it only display one record.
anyone has idea whats wrong with my code?
any help would be greatly appreciated. Thank you!
Upvotes: 0
Views: 132
Reputation: 44844
You need to declare $data
outside the loop, you are doing inside the loop and hence inside each loop its getting over-written and you are getting the last value.
$data = '';
while($row = mysqli_fetch_assoc($result)){
$data .= '<article>';
$data .= '<h3>' . $row['title'] . '</h3>';
$data .= '<p>' . $row['content'] . '</p>';
$data .= '<footer>By: ' . $row['whoposted'] . ' / ' . $row['dateposted'] . '</footer>';
$data .= '</article>';
}
Upvotes: 3