0

I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:

$result = mysql_query("select * from table1");

while($row = mysql_fetch_array($result))
{
    echo $row["field1"].','.$row["field2"];
}

In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?

I think the answer is a foreach($row as....) - but not sure where to go from there.

Foon
  • 6,148
  • 11
  • 40
  • 42
user1676300
  • 135
  • 7
  • 4
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and consider using [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 05 '15 at 20:41
  • Wouldn't echo $row not do the trick ? –  May 05 '15 at 20:42
  • `foreach($row as $r){echo $r.',';}` –  May 05 '15 at 20:43

2 Answers2

2

Yep you can do a foreach but if you just want to display your values in a CSV style you can do :

$firstRow = true;
while($row = mysql_fetch_array($result))
{
    if ($firstRow) {
        $firstRow = false;
        $columns = array_keys($row);
        // prints all the column names
        echo implode(',', $columns);
    }

    // print all the values
    echo implode(',', $row);
}

If you want more control over what you output you can use a foreach :

while($row = mysql_fetch_array($result))
{
    foreach ($row as $column => $value) {
        echo $column.' : '.$value."\n";
    }
}
Alfwed
  • 3,307
  • 2
  • 18
  • 20
1

You'll want to count the $row array

while($row = mysql_fetch_array($result))
{
    $columns = count($row);
    for($i = 0; $i < $columns; $i++)
    {
        echo $row[$i].',';
    }
}

Or you can use foreach() as @Dagon has pointed out -

while($row = mysql_fetch_array($result))
{
    foreach($row as $column)
    {
        echo $column . ',';
    {
}

Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119