CzechJura CzechJura - 1 year ago 122
HTML Question

Display data from database in HTML page

I would like to display data from my database on page load, but I don't know how and I didn't found any functional way. Inserting works fine.

Here is my HTML code for data inserting:

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor,">
<form action="insert.php" method="post">
<label for="snapname">Name:</label>
<input type="text" name="snapname">
<label for="age">Age:</label>
<input type="text" name="age">
<input type="submit" value="odeslat">

PHP for connect and insert data to database:

$servername = "localhost";
$username = "admin";
$password = "***";
$dbname = "db1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Could not connect to server: " . $conn->connect_error);
$first_name = mysqli_real_escape_string($conn, $_POST['snapname']);
$last_name = mysqli_real_escape_string($conn, $_POST['age']);

$Jmeno = $_POST['snapname'];
$Vek = $_POST['age'];

$sql = "INSERT INTO snapy (ID, username, age, date)
VALUES (0, '$Jmeno', '$Vek', CURRENT_TIMESTAMP)";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;


Can someone help me with displaying data in HTML file?

Answer Source

You need to run a SELECT-request. Since you are using MySQLi you want to use something like:

$sql = "SELECT * FROM snapy";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["age"]. " yo<br>";
} else {
    echo "0 results";

Found here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download