Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to get the php output into an HTML table. The mysql code outputs the data from the table pet, but when i add the table code as shown below it stops working and gives errors. How do I get the table pet output into an HTML table? thanks

<html>
<head>
<title> php test script - hope this works </title>
</head>
<body>
<h1>php & mysql connection</h1>
<hr>
<?php
$db_host = "localhost";
$db_username = "vistor";
$db_pass = "visitor";
$db_name = "test";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $db->query('SELECT * FROM pet');
echo "<table border = '2'>"
<tr>
<th>id</th>
<th>name</th>
</tr>
while ($row = $query->fetch()) 
{
echo "<tr>";
echo "<td>" . $row['id'] ."</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "</tr>;
}
echo "</table>";
?>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
685 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your issues lies in your formatting and confusion between the use of the echo command and non PHP wrapped HTML. Code should read as follows when properly formatted.

<?php
$db_host = "localhost";
$db_username = "vistor";
$db_pass = "visitor";
$db_name = "test";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $db->query('SELECT * FROM pet');
?>

<html>
<head>
<title> php test script - hope this works </title>
</head>
<body>
<h1>php & mysql connection</h1>
<hr>
<table border = '2'>
<tr>
<th>id</th>
<th>name</th>
</tr>

<?php
while ($row = $query->fetch()) 
{
    echo "<tr>";
    echo "<td>" . $row['id'] ."</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['price'] . "</td>";
    echo "</tr>";
}
?>

</table>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...