Forum Moderators: coopster

Message Too Old, No Replies

mysql fetch array() returning duplicate data

mysql fetch duplicate error

         

ultrageek

5:30 am on Nov 23, 2009 (gmt 0)

10+ Year Member



I have an issue with the following code...
Assume I have a mysql table like the following...

TABLE: person
col fname
col lname
col contact
col id.

$data passedin is a mysql resource.
$head is an array of table headings (nullable)
query = "select * from person order by lname"
mysql = 2.10
problem occurs with php 4 and 5

I expect the code to output a table like this...

header1 (header2 header3)
fname1 lname1 contact1, id1
fname2 lname2 contact2, id2
fname3 lname3 contact3, id3

What I actually get is....

header1 (header2 header3)
fname1 fname1 lname1 lname1 contact1 contact1 id1 id1
fname2 fname2 lname2 lname2 contact2 contact2 id2 id2
fname3 fname3 lname3 lname3 contact3 contact3 id3 id3
...

Has anyone seen this?

<?php
function build_table($data,$head = null)
{
echo "<table>";
if ($head)
{
foreach ($head as $h)
echo "<th>".$h."</th>\n";
}
if (is_resource($data))
{
mysql_data_seek($data,0);
while($row = mysql_fetch_array($data))
{
echo "<tr>";
foreach($row as $r)
{
echo "<td>".($r)."</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
}
}
?>

Psychopsia

10:19 pm on Nov 24, 2009 (gmt 0)

10+ Year Member



You should call mysql_fetch_array function as:

mysql_fetch_array($data, MYSQL_ASSOC);

By default function second arg uses MYSQL_BOTH, that return MYSQL_ASSOC and MYSQL_NUM.

Hope this helps.

ultrageek

12:16 am on Nov 25, 2009 (gmt 0)

10+ Year Member



Psychopsia,

You rule! That's exactly what I missed. I appreciate the insight.
I spent the weekend reading the mysql docs, and didn't see it.