Page 1 of 1

mysql fetch array gives double outputs

Posted: Wed Sep 16, 2009 12:28 pm
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

Re: mysql fetch array gives double outputs

Posted: Wed Sep 16, 2009 1:34 pm
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 :)

Re: mysql fetch array gives double outputs

Posted: Wed Sep 16, 2009 1:42 pm
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().