MySQL – PHP Print Records to HTML (mysqli)

You can use PHP to access records in a MySQL database and then print them out in HTML.

phpSelect.php

<?php

$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";

$conn = new mysqli($servername, $username, $password, $db);

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

$sql = "select * from parts";
$result = $conn->query($sql);

if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
	echo $row["part_name"] ."  " .$row["part_price"]. "<br>";
}
} else {
	echo "0 records";
}
$conn->close();

?>

phpSelectTable.php

<?php

$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";

$conn = new mysqli($servername, $username, $password, $db);

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

$sql = "select * from parts";
$result = $conn->query($sql);

echo "<table><tr><th>.  Name  </th><th>Price</th></tr>";
if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
	echo "<tr><td>". $row["part_name"] . "</td><td>".$row["part_price"]. "</td></tr>";
}
} else {
	echo "0 records";
}
echo "</table>";

$conn->close();

?>

Be the first to comment

Leave a Reply