[英]Echo PHP to HTML table
Having issues with this PHP echo while loop. 与此PHP有关的问题在while循环中回显。 What am I doing wrong? 我究竟做错了什么? Page won't load due to it. 页面因此无法加载。
$query = mysql_query("SELECT * FROM `uploads`");
while($row = mysql_fetch_assoc($query)) //while loop
{
$id = $row['id']; //get ID
$name = $row['name']; //get name
//variable for getting name and ID
// echo out all songs and display with name. //回显所有歌曲并显示名称。
echo "<table>";
echo "<tr>";
echo "<td>Name</td>";
echo "<td><a href='listen.php?id=$id' target='_new' >$name </a></td>";
echo "</tr>";
echo "</table>";
Try to separate your HTML
from PHP
for easy debugging and your code will be a lot cleaner 尝试将HTML
和PHP
分开以方便调试,并且代码将更加简洁
<table>
<tr>
<th>Name</th>
</tr>
<?php
while ($row = $result->fetch_assoc()) : ?>
<tr>
<td><a href='listen.php?id=<?php echo $row['id']; ?>' target='_new' ><?php echo $row['name']; ?></a></td>
</tr>
<?php endwhile; ?>
</table>
In this code you are attempting to link to an $id and $name, one can only assume, from a mysqli_query function which you have omitted. 在这段代码中,您试图从一个省略的mysqli_query函数链接到一个$ id和$ name,它们只能假设一个。
However, I can see what you are attempting. 但是,我可以看到您正在尝试什么。 Firstly, you need not specify echo on every line. 首先,您不必在每一行上都指定echo。 Applying this to a snippet of your code changing 将其应用于代码更改的代码段
<?php
echo "<table>";
echo "<tr>";
?>
to 至
<?php
echo "<table>
<tr>";
?>
will produce the same result and save some typing. 将产生相同的结果并保存一些输入。
This is what you are looking for. 这就是您要寻找的。
<?php
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
$sql = "SELECT * FROM `uploads`";
$qry = mysqli_query($con,$sql) or die(mysqli_error($con));
$table_content = "";
while($row = mysqli_fetch_assoc($qry)){
$id = $row['id'];
$name = $row['name'];
$table_content .= "<tr>
<td>Name</td>
<td><a href='listen.php?id=$id' target='_new'>$name</a></td>
</tr>";
}
echo "<table>".$table_content."</table>";
?>
This will produce a table with 2 columns, the first having the value 'Name' for each column, the second a link to the record ID with the records name as the text. 这将产生一个包含2列的表格,第一列的每一列都具有值“ Name”,第二列是指向以记录名称为文本的记录ID的链接。
If you are after a table heading called 'Name' you will need to a row with 如果您在名为“名称”的表标题之后,则需要使用
<th>Name</th>
Here I use mysqli_query as mysql_query is deprecated. 在这里,我不建议使用mysqliquery ,而使用mysqli_query 。 mysqli_error is useful to include when querying your database. mysqli_error在查询数据库时非常有用。 In the event the connection fails to execute the query it will provide a (not always useful) error, but atleast point you towads a solution. 如果连接无法执行查询,它将提供(并非总是有用的)错误,但至少会提示您解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.