Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Weird behavior with mysql_fetch_array();

Status
Not open for further replies.

symbiotic

Technical User
Jan 17, 2003
28
GB
Hi all,
I'm new to php. From an asp/vbs/mssql background I found it incredibly easy to learn and work with, but I have noticed some peculiarities, one of which is this.

This code should query a database for all the entries in table accounts, print a table row for each entry in the sql table, and a table cell for each column in the sql table:

$query = "Select * from accounts;";
if (!($result = mysql_query($query, $conn)))
die("Could not process request");

while ($row = @ mysql_fetch_array($result))
{
print(&quot;<tr>&quot;);
foreach($row as $fieldname)
{
print(&quot;<td>&quot; . $fieldname . &quot;</td>&quot;);
}
print(&quot;</tr>&quot;);
}

However what I found is that for some reason, each column was being printed twice (the foreach loop was executing twice for each $fieldname). I didn't let it baffle me for long, it was easily fixed by using MYSQL_BOTH in mysql_fetch_array and by adding a counter to the loop and using $row[$cnt] instead of $fieldname. However, anal as I am, it will forever bother me until I figure out why that happened. I don't see anything in the code that should have caused it.

Thanks for any feedback
 
mysql_fetch_array() stores the row data both as array indices and as associative arrays.

Your forach loop was looping through the values in the array. Since each value is stored in the array twice, you got each one printed out twice.

Actually, MYSQL_BOTH is the default -- using it didn't fix anything. What fixed the problem was your using a counter and referring only to the numerical array indices. Want the best answers? Ask the best questions: TANSTAAFL!
 
Excellent explanation, sleipnir, should have known thats what it was. The PHP manual mentions that the data is stored both as indices and associative arrays, but it didn't click that thats what would cause the behavior. I guess I coded it correctly the second time, it always bothers me when I have to use brute force(stupidity) to get something to work. Appreciate it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top