tags:

views:

163

answers:

2

Hi, I have a simple query that I can't for the life of my get to print out on my page:

$results = mysql_query("SELECT * FROM andyasks ORDER BY date");
$test = mysql_fetch_array($results, MYSQL_BOTH);
foreach ($test as $row){
    print($row[questions]);
}

What this outputs is (unpredictably, to my eyes) just the first letter of each table field, for just the first two rows. So a 75 row table x 5 columns should show 75 "questions" lining up, but instead it shows "00WWFFAA00" which is the first letter of each cell of the first two rows. What's going on?

+5  A: 

Try this.

$results = mysql_query("SELECT * FROM andyasks ORDER BY date");

while($row = mysql_fetch_array($results))
{
    print($row["questions"]);
}

The reason is that you will only do one fetch with

$test = mysql_fetch_array($results, MYSQL_BOTH);

That's why you need to have it in a while loop. It fetches one row, and the while loop will terminate when there are no more rows (since it returns false when there are no more rows).

Ólafur Waage
+4  A: 

Just to explain what's wrong with your code...

Your code is fetching only the first row into the $test variable. This array contains each column twice - keyed by both index and by name (which is what MYSQL_BOTH does). If you insert print_r($test); before the loop it'll dump the contents of the array, so you can see what's happening.

What your loop does is go through each column and extract its value into $row as a string. When you use array syntax (i.e. $row["questions"]) on a variable that contains a string, PHP extracts a character at the index you selected. Since "question" is not a number, it evaluates to 0, which is why you get the first letter of each column.

Ólafur Waage has the correct syntax for what you're trying to do.

grahamparks
I appreciate the explanation; I'll always prefer to learn why rather than just cut/paste. Regards.
Alex Mcp