Having issues with this PHP echo while loop. 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
<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.
However, I can see what you are attempting. Firstly, you need not specify echo on every line. 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.
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. mysqli_error is useful to include when querying your database. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.