Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML table from sql table

I have a table in a SQL database with the following fields: ID, Name, Email, University, Languages, and Experience. I want to create an html table that fetches data from SQL and outputs the last 10 results? How would I do that?

I'm sorry if this is a very simple question, I have very little knowledge in PHP and SQL.

Here's the code I have right now that just displays the name and not in a table:

    <html>
    <head>
        <title>Last 5 Results</title>
    </head>
    <body>
        <?php
            $connect = mysql_connect("localhost","root", "root");
            if (!$connect) {
                die(mysql_error());
            }
            mysql_select_db("apploymentdevs");
            $results = mysql_query("SELECT * FROM demo");
            while($row = mysql_fetch_array($results)) {

                echo $row['Name'] . "</br>";


            ?>
    </body>
</html>
like image 232
Aloke Desai Avatar asked Aug 13 '12 23:08

Aloke Desai


2 Answers

Here is something that should help you to create the table and get more knowledge of php and mysql.

Also you should move your connection logic and query to the beginning of your process, thus avoiding errors while loading the page and showing a more accurate error than just the mysql_error.

Edit: If your ids are incrementing, then you could add the ORDER BY clause,
change: SELECT * FROM demo LIMIT 10 to: SELECT * FROM demo LIMIT 10 ORDER BY id

<html>
    <head>
        <title>Last 10 Results</title>
    </head>
    <body>
        <table>
        <thead>
            <tr>
                <td>Id</td>
                <td>Name</td>
            </tr>
        </thead>
        <tbody>
        <?php
            $connect = mysql_connect("localhost","root", "root");
            if (!$connect) {
                die(mysql_error());
            }
            mysql_select_db("apploymentdevs");
            $results = mysql_query("SELECT * FROM demo LIMIT 10");
            while($row = mysql_fetch_array($results)) {
            ?>
                <tr>
                    <td><?php echo $row['Id']?></td>
                    <td><?php echo $row['Name']?></td>
                </tr>

            <?php
            }
            ?>
            </tbody>
            </table>
    </body>
</html>
like image 105
Josejulio Avatar answered Sep 21 '22 14:09

Josejulio


An option requiring you to encode the data in the database to JSON: http://www.jeasyui.com/documentation/datagrid.php

But this looks a lot more promising: http://phpgrid.com/

like image 23
peterrus Avatar answered Sep 22 '22 14:09

peterrus