Skip to content Skip to sidebar Skip to footer

Creating Html Table With Php Output

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 er

Solution 1:

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><tableborder = '2'><tr><th>id</th><th>name</th></tr><?phpwhile ($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>

Solution 2:

<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');
 ?><tableborder ="2"><tr><th>id</th><th>name</th></tr><?phpwhile ($row = $query->fetch()) 
{
?><tr><td><?phpecho$row['id'];?></td><td><?phpecho$row['name'];?></td><td><?phpecho$row['price']; ?></td></tr><?php } ?></table></body></html>

Solution 3:

Your quoting is wrong.

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>";

The quote at the end of the first echo line belongs after the </tr>. And the last echo "</tr>"; line was missing a closing quote.

You should be able to see these problems from the syntax highlighting in the question.

Post a Comment for "Creating Html Table With Php Output"