tags:

views:

32

answers:

2

Hi.

I've got a database table with at least three rows in it. From php, I have successfully connected to my db and extracted all table information with 'SELECT * from mytable' .

Now I want to loop through first each row, and then each cell, printing out the contents of each cell.

I know this might be a simple task for a more experienced programmer, but I can't figure it out, and I can't find any examples online and it's driving me stark raving bonkers.

How can I do this ?

+3  A: 

You could use a for each loop...

//Do the query
$query = "SELECT * FROM table";
$result = mysql_query($query);
//iterate over all the rows
while($row = mysql_fetch_assoc($result)){
    //iterate over all the fields
    foreach($row as $key => $val){
        //generate output
        echo $key . ": " . $val . "<BR />";
    }
}

Haven't tested it, so there may be a syntax error in it, but this is the main idea

Lex
Thanks Lex. This is what I ended up using.I modified it so to output everthing in paragraphs and divs.
roberto
Great, feel free to accept my answer ;)
Lex
+3  A: 

There are a couple of examples in the manual that could help you with that ; for instance, on the manual page of mysql_query (quoting, and adapting a bit) :

You first have to execute the query :

$result = mysql_query('SELECT * from mytable');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

Note that dying in case of an error, and echoing the error-message, is OK while developping -- but you shouldn't do that in a production environment !


And, then, you have to loop over the lines of results, fetching them one at a time :

while ($row = mysql_fetch_assoc($result)) {
    // Use the data in $row
}


And, inside this loop, as $row is an array, you can iterate over its content with a foreach loop :

foreach ($row as $name => $value) {
    echo "column $name contains $value<br />";
}


Note : at this point, you should really invest some time going through a couple of sections of the PHP manual : it will take some time, yes ; but it will definitely help you, and will not be wasted time :-)

Pascal MARTIN