CzechJura CzechJura - 3 months ago 22
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:

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


PHP for connect and insert data to database:

<?php
$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;
}

$conn->close();
?>


Can someone help me with displaying data in HTML file?

Answer

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: http://www.w3schools.com/php/php_mysql_select.asp