简体   繁体   中英

Echo html table with specific field

I am fairly new at PHP. And I can't seem to find the issue with my code here. I am trying to SELECT specific rows from my table and echo it in my HTML table using my own headers. I keep getting No data available in table message.

<?php
       $db_host = 'localhost';
       $db_user = 'my user';
       $db_pwd = 'my pwd';

       $database = 'my db';
       $table = 'client';

    if (!mysql_connect($db_host, $db_user, $db_pwd))
                    die("Can't connect to database");

                if (!mysql_select_db($database))
                    die("Can't select database");

                // sending query
                $result = mysql_query("SELECT 'id', 'datecreated', FROM {$table}");
                if (!$result) {
                    die("Query to show fields from table failed");
                }

                $fields_num = mysql_num_fields($result);

                echo "<table class='table table-bordered table-striped mb-none' id='datatable-tabletools' data-swf-path='assets/vendor/jquery-datatables/extras/TableTools/swf/copy_csv_xls_pdf.swf' >";
                // printing table headers
                echo "<thead>";
                echo "<th>Client ID</th>";
                echo "<th>Sign Up Date</th>";
                echo "</thead>";
                // printing table rows
                if ($results->num_rows > 0) {
                while ($row = $results->fetch_assoc()){

                }
                    echo "<tbody>";
                    echo "<tr>";


                    echo "<td>".$row["id"]."</td>";
                    echo "<td>".$row["datecreated"]."</td>";



                    echo "</tr>";
                    echo "</tbody>";
                }
                mysql_free_result($result);
                ?>

Change the order your code around the while loop to:

if ($fields_num > 0) {
    echo "<tbody>";
    while ($row = mysql_fetch_assoc($result)) {

        echo "<tr>
            <td>".$row["id"]."</td>
            <td>".$row["datecreated"]."</td>
            </tr>";

    }
    echo "</tbody>";
}

At the moment you aren't actually doing anything with the data you're retrieving.

And FYI - mysql is deprecated, you should use mysqli

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM