Reputation: 1962
Okay I have been working on a website but I keep on having an odd display whenever I use a foreach loop on some data from a data base. I get this:
2
Posted By: 2
22
Posted By: 2
2H
Posted By: H
HH
Posted By: H
HT
Posted By: T
TT
Posted By: T
TA
Posted By: A
AA
Posted By: A
A
When I use this loop:
$res = mysql_query("SELECT * FROM `fcat`");
$resa = mysql_fetch_array($res);
if(!empty($resa)){
foreach($resa as $j){
echo $j['title']."<br />";
echo "Posted By: ".$j['poster']."<br />";
echo $j['info'];
}
}else{
echo "Nothing.";
}
On this database:
id is an int(11)= 2
title is a varchar(65)= Hi
info is a text= Test
creator is a text= Admin
Thanks!
Upvotes: 0
Views: 61
Reputation: 7675
I think this may help you:
$res = mysql_query("SELECT * FROM `fcat`");
if(mysql_num_rows($res)>0){
while($j = mysql_fetch_array($res)){
echo $j['title']."<br />";
echo "Posted By: ".$j['poster']."<br />";
echo $j['info'];
}
}else{
echo "Nothing.";
}
Upvotes: 1
Reputation: 836
Try this:
$res = mysql_query("SELECT * FROM `fcat`");
while($j = mysql_fetch_array($res)){
echo $j['title']."<br />";
echo "Posted By: ".$j['poster']."<br />";
echo $j['info'];
}
Upvotes: 0
Reputation: 47311
mysql_fetch_array return an array with both numeric and associate key
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
so, change it to
mysql_fetch_array($res, MYSQL_ASSOC);
Upvotes: 0