user6394840 user6394840 - 2 years ago 103
MySQL Question

Alternative to while loop

I am a newbie. I asked a question earlier regarding retrieving duplicates of the data i need from the db, for example the opening times from each takeaway duplicating on each take away (see image below); and i received a very helpful comment. The comment suggested that my while loop is causing my problem of query results duplication, as it is overriding my data.

duplication example

After looking at my code and working out which while loops are causing this problem (as I have a few), and playing around with them to understand my issue, I am now intrigued to know what loop can be used in replacement or as alternative to a while loop.

$rest_query = "SELECT Resturant_ID FROM Rest_Details";
$res_results = $dbc->query($rest_query);

//while($row_results = $res_results->fetch_assoc()){
$row_results = $res_results->fetch_assoc();{
$rests = $row_results['Resturant_ID'];

Above is one of the while loops I have removed, I know I will need a loop to gain all the information needed. And I do not know the number of repetitions I will need, therefore a for loop is not helpful.

Just trying to gain a better understanding, as I am building this website to teach myself.

Answer Source
"SELECT DISTINCT my_column_with_duplicates FROM Rest_Details"

and then

while($row_results = $res_results->fetch_assoc())

will work just fine.

Also there are other ways like $res_results->fetchAll() to get all the results in an array then use foreach loop. Just an idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download