Reputation: 567
I'm having a little issue with looping through my database retrieving results, I understand why I am getting the issue but not too sure on how to implement the solution as my PHP is not the greatest. I have looked through the forums but couldn't find anything to address my problem.
From below my output would give me 12 results when only I want 6 results 2 items each: for each loop is counting 12 items in array which makes sense so it will out put 12 times giving me duplicates of each. how am I best to handle this issue.
MyTable1: myTable2:
| ID | Name | | NameID | Details |
|--------|--------| |----------|-------------------|
| 0 | bob | | 0 | lives in the city |
| 1 | david | | 1 | lives in a caravan|
------------------- --------------------------------
My MSQLI query:
$qryRandom = "SELECT MyTable1.ID, MyTable2.Details
FROM MyTable1
INNER JOIN MyTable2
ON MyTable1.ID=MyTable2.NameID
ORDER BY RAND()
LIMIT 6;";
My PHP( generall example).
$resultR= $con->query($qryRandom) or die($mysqli->error.__LINE__);
while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
{
foreach ( $row as $key=>$value ){ // loops 12 times here as there is 6 items x 2 values
echo $key.": ".$value."<br>";
}
}
result outputs:
bob lives in city
bob lives in city
David lives in caravan
David lives in caravan
john lives in the car
john lives in the car // doubles of each entry is my issue
// hope I was thorough and provided enough info for my scenario.
Upvotes: 0
Views: 149
Reputation: 567
The solution I came up with works how ever I am still not happy with it;
while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
{
for ($i = 0; $i<1;$i++){
echo $row['name'].$row['details']."<br>";
}
}
Im more then sure there is a better approach to this issue.
Upvotes: 1