AmraAz AmraAz - 4 months ago 18
SQL Question

How to show table from MySQL database using php and html

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {

die ("Umro!");

}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>


Thank you!

Answer

Do you want to show the table as a HTML table or just an array?

The following is what I did to display my table as a HTML table:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,;
if (!$conn){
    die('cannot connect to mysql');
}

$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {

    echo("<div class = 'data_wrapper'>");

    // Display Header of the table

    $fieldcount=mysqli_num_fields($result); //value = number of columns

    $row = mysqli_fetch_assoc($result);     //Fetch a result row as an associative array:

        //array to string conversion

        echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");

        echo("<thead> <tr>");

        foreach($row as $item){

            echo "<th>" .$item. "</th>";
        }

        echo("</tr> </thead>");


        //Footer
        echo("<tfoot> <tr>");

        foreach($row as $item){

            echo "<th>" .$item. "</th>";
        }

        echo("</tr> </tfoot>");



        //Display Data within the table
        echo("<tbody>");
        while ($row = mysqli_fetch_assoc($result)){
                echo "<tr>";
                foreach ($row as $item){
                    echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
                    //Editable data should be constricted, int = numbers only, string = words, date = date
            }
            echo "</tr>";
        }
        echo("<tbody>");
        echo "</table>";
        echo("</div>");

    }

The following is just displaying as an array:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,;

if (!$conn){
    die('cannot connect to mysql');
}
 $query = "SELECT * FROM $selectedTable";

 if ($result = mysqli_query($conn , $query)) {
    while ($row = mysqli_fetch_array($result)){
       print_r($row);
    }
 }