It's my first post, and it's good to know you're out there :-)
I've been teaching myself PHP and MySQL over the past few months, and have got to the point where I have been able to take on my first project: an online survey facility for an accountancy firm where a friend of mine works. I've now built the database tables and most of the pages which interact with them, and everything works fine - except, that is, for one part of the final page, and I'd really appreciate any suggestions you have:
My friend needs a feature which would write all the database's contents to a tab-delimited text file, which he could then download and import into Excel. I've created a PHP page which achieves this, but I have a problem with the foreach operation that I'm using to loop through all the database fields.
This is the part of the code which is causing the trouble:
// Loop through each item in each row of the array, and write rows to file
while ($res_array = mysql_fetch_array($result)) {
$row = "";
foreach ($res_array as $value) {
$row .= "$key:$value\t";
} // end of Foreach
$row .= "\n";
fwrite($file, "$row");
} // End of While
fclose($file); // Close text file
Basically, the page works as I intended, except that each field is printed twice (e.g. answer1, answer1, answer2, answer2, etc.). To try and find out the cas, I changed the foreach condition to
foreach ($res_array as $key => $value)
and found that the foreach loop is retrieving each database field as both a numbered key and a name key:
0:answer1, field0:answer1, 1:answer2, field1:answer2, etc.
Please can anyone suggest how I can retrieve only the named keys, so I only get one copy of each field?
(I looked through this forum, and found a couple of posts which identify the problem's cause, but I didn't find any suggestions on how to correct it. If I didn't look hard enough, and anyone can point me to an existing post which answers the above, I'd be really grateful :-) )
Many thanks in advance for your help.
All the best,
Tim.