mysql fetch array gives double outputs

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jmoncrieff
Forum Newbie
Posts: 3
Joined: Fri Sep 11, 2009 3:03 pm

mysql fetch array gives double outputs

Post by jmoncrieff »

I am a problem, I am trying to create a table and I using a while and foreach statement every thing works but I am get double results Ie
record1
recrord1
record2
record2.
etc..
has any one seen this before?

Code: Select all

<?php>
                
                        $sql="SELECT agency_id from agency";
                        $result=mysql_query($sql,$db);
                    while ($rows= mysql_fetch_array($result)){
                        foreach($rows as $agency){
                        print  "<table border='2'>";
                        print "<tr><td valign='top' width='200'>";
                        $sdc->get_agency_name($agency);
                        echo "</td><td valign='top' width='200'>";
                        $sdc->get_agency_image($agency);
                        echo "</td><td colspan=3>";
                        $sdc->get_agency_services_list($agency);
                        echo "<hr>";
                        $sdc->get_agency_zone_list($agency);
                        echo "</td></tr>";
                        echo "<tr><td>";
                        $sdc->get_agency_address_block($agency);
                        echo "</td></td>";          
                        $sdc->get_agency_desc($agency); //check this function need row output not a table ouput
                                }
                    }
               
Jeff
ricehigh
Forum Newbie
Posts: 21
Joined: Mon Sep 14, 2009 5:18 pm

Re: mysql fetch array gives double outputs

Post by ricehigh »

You're getting a double result because when you fetch an array from a database, the data will be put in both ordered with numbers and ordered with strings appropriate to the coloumn of the database.
Therefore the foreach statement is an unwise choice when fetching data from a database :)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: mysql fetch array gives double outputs

Post by pickle »

ricehigh wrote:Therefore the foreach statement is an unwise choice when fetching data from a database :)
Not at all. In fact, it's the ideal solution in this situation.

Part of what ~ricehigh said is correct though. Your call to mysql_fetch_array() is retrieving the elements and putting them in the array twice - once with a numeric key and once with an associative key. I'd look into using mysql_fetch_assoc().
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply