Search code examples
phphtmlsqldatabase-table

PHP: Function to plot any query result in a table


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


Solution

  • 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>";
    }