1

I'm relatively new to using PHP and have been working on using it to fetch data from a database. I have been able to plot queries in tables quite easily when I know the number of columns that need to be plotted, like below:

        echo "<table border='1'>";
            echo "<tr><td align='center' colspan='6'><b>All ".$catDesc." CD's</b></td></tr>";   

            while ($row = mysql_fetch_array($result)){
                echo "<tr bgcolor='#fff'>
                        <td>".$row['catDesc']."</td>
                        <td>".$row['CDTitle']."</td>
                        <td>".$row['CDYear']."</td>
                        <td>".$row['artistName']."</td>
                        <td>£".$row['CDPrice']."</td>
                        <td>".$row['PubName'].", ".$row['location']."</td>
                    </tr>";
            }
        echo "</table>";

I was wondering if there is any way of writing some code in a separate function that would plot the result of any query that it was given regardless of the number of field/ columns the query result held.

Thank you for any advice or code you'd like to share.

Jonny

Raidri
  • 17,258
  • 9
  • 62
  • 65
JonnyIrving
  • 753
  • 2
  • 8
  • 18

1 Answers1

4

Within the while-loop you could iterate over the $row-variable and create a new td-element each time:

while($row = mysql_fetch_assoc($result))
{
    echo "<tr bgcolor='#fff'>";

    foreach($row AS $key => $value)
    {
         echo "<td>$value</td>";
    }

    echo "</tr>";
}
Fidi
  • 5,754
  • 1
  • 18
  • 25
  • and use http://php.net/manual/en/function.array-keys.php from first row for column names – n00b Mar 10 '11 at 13:57
  • 1
    This is the way to do it. Definitely notice the use of `mysql_fetch_assoc()`. `mysql_fetch_array()` will give you double values since it provides numeric and string indexes for each value. – Scott Saunders Mar 10 '11 at 13:59
  • You're right. I corrected the mysql_fetch_array! Just copied the raw body from the question without further checking. Thank you :) – Fidi Mar 10 '11 at 14:18
  • Thanks for this everyone. I'll look forward to giving it a try. – JonnyIrving Mar 10 '11 at 14:37