Mohamed
Mohamed

Reputation: 57

Displaying an associative array in PHP

I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the array so another function can display it. I need a way to display the returned assoc array. This should be a different function from the first one

Upvotes: 2

Views: 13501

Answers (6)

Freyja
Freyja

Reputation: 40884

If you just want information about what is in the array (for debugging purposes), you can use print_r($array) or var_dump($array), or var_export($array) to print it in PHP's array format.

If you want nicely formatted output, you might want to do something like:

<table border="1">
  <?php
  foreach($array as $name => $value) {
    echo "<tr><th>".htmlspecialchars($name).
        "</th><td>".htmlspecialchars($value)."</th></tr>";
  }
  ?>
</table>

This will, as you might already see, print a nicely formatted table with the names in the left column and the values in the right column.

Upvotes: 2

Tarka
Tarka

Reputation: 4043

The following should work:

$rows = mysql_query("select * from whatever");
if ($rows) {
    $header = true;
    while ($record = mysql_fetch_assoc($rows)) {
        if ($header) {
            echo '<tr>';
            foreach (array_keys($record) AS $col) {
                echo '<td>'.htmlspecialchars($col).'</td>';
            }
            echo '</tr>';
            $header = false;
        }
        echo '<tr>';
        foreach (array_values($record) AS $col) {
            echo '<td>'.htmlspecialchars($col).'</td>';
        }
        echo '</tr>';
    }
}

(Yes, blatant mod of Fosco's code)

This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.

Upvotes: 0

fredley
fredley

Reputation: 33921

Assuming you've made the call, and got $result back:

$array = new array();
while($row = mysql_fetch_assoc($result)){
  $array[] = $row;
}
return $array;

Upvotes: 0

Artefacto
Artefacto

Reputation: 97835

while ($row = mysql_fetch_assoc($result)) {
    foreach ($row as $column => $value) {
        //Column name is in $column, value in $value
        //do displaying here
    }
}

If this is a new program, consider using the mysqli extension instead.

Upvotes: 1

fredley
fredley

Reputation: 33921

print_r($array) will give nicely formatted (textually, not html) output.

Upvotes: 2

Fosco
Fosco

Reputation: 38526

This should get you going:

$rows = mysql_query("select * from whatever");
if ($rows) {
   while ($record = mysql_fetch_array($rows)) {
       echo $record["column1"];
       echo $record["column2"];
       // or you could just var_dump($record); to see what came back...
   }
}

Upvotes: 0

Related Questions