使用php输出创建HTML表

时间:2014-11-20 11:05:49

标签: php html mysql

我正在尝试将php输出转换为HTML表格。 mysql代码输出表pet中的数据,但是当我添加如下所示的表代码时,它会停止工作并产生错误。如何将表格宠物输出到HTML表格中?感谢

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

3 个答案:

答案 0 :(得分:3)

您的问题在于使用echo命令和非PHP包装HTML之间的格式化和混淆。正确格式化后,代码应如下所示。

<?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>

答案 1 :(得分:1)

<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');
 ?>


<table border ="2">
<tr>
<th>id</th>
<th>name</th>
</tr>


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

答案 2 :(得分:0)

你的报价错了。

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

第一行echo行末尾的引号属于</tr>之后。并且最后echo "</tr>";行缺少结束语。

您应该能够从问题中的语法突出显示中看到这些问题。