mysql_query row values iteration problem
I have a problem iterating through an sql query:
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_array($result)) {
开发者_运维技巧// this returns 3 rows
foreach ($row as $values)
{
//fputcsv($a_csv, $values;
echo $values;
}
}
The script iterates fine but it appears to be going through each row twice. So what I receive in output is the following:
value1value1value2value2value3value3
I'm not sure why this is - could anyone explain please?
Thankyou
mysql_fetch_array
fetches both the named & the numerical keys. Use either mysql_fetch_assoc
or mysql_fetch_row
.
$result = mysql_query("SELECT * FROM transactions");
//return an associative array
while($row = mysql_fetch_assoc($result)) {
// this returns 3 rows
$values = "{$row["name_of_column1"]}, {$row["name_of_column2"]}, {$row["name_of_column3"]}";
//fputcsv($a_csv, $values;
//print the whole row array
print_r($row);
//echo value in format value1, value2, value3
echo $values;
}
You need to access $row
like this $row[0]
And $row shouldn't be in a foreach() itself unless it too is some kind of array you need to iterate through.
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_row($result))
{
echo $row[0];
echo $row[1];
// ... etc.
}
精彩评论