我可以将$变量变成表格吗?

时间:2013-03-22 02:01:35

标签: php html mysql

我按照在线教程创建了一个管理员后端,我在php页面的HTML标签之前得到了这段代码:

<?php 
$product_list = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysql_num_rows($sql); // count the output amount

if ($productCount > 0)
{
  while($row = mysql_fetch_array($sql))
  { 
    $id = $row["id"];
    $product_name = $row["product_name"];
    $price = $row["price"];
    $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
    $product_list .= "Product ID: $id - <strong>$product_name</strong> - $$price - <em>Added $date_added</em> &nbsp; &nbsp; &nbsp; <a href='inventory_edit.php?pid=$id'>edit</a> &bull; <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
  }
} 
else 
{
  $product_list = "You have no products listed in your store yet";
}
?>

当我将<?php echo $product_list; ?>放在页面内容上时,我会检索这样的列表结果:

Product ID: 1 - Strawberries - $10 - Added Mar 22, 2013       edit • delete
Product ID: 2 - Apples 1 - $10 - Added Mar 22, 2013       edit • delete

我想要的是将它放在一个对称的列表视图中,就像一张表左右一样,以显示结果和编辑/删除选项。试图在$product_list上放置一个包含1行和5列的表,但没有成功。

1 个答案:

答案 0 :(得分:1)

$mysqli = new mysqli("localhost", "username", "password", "database_name");

$query = "SELECT * FROM products ORDER BY date_added DESC";
$result = $mysqli->query($query);

$product_list = '<table>';
$product_list .= '<thead><tr>ID</tr><tr>Name</tr><tr>Price</tr><tr>Added</tr></thead>';
$product_list .= '<tbody>';

while($row = $result->fetch_array()){ 
  $id = $row["id"];
  $product_name = $row["product_name"];
  $price = $row["price"];
  $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
  $product_list .= "<tr><td>$id</td><td>$product_name</td><td>$price</td>    <td>$date_added</td></tr>";
 }

 $product_list .= '</tbody>';
 $product_list .= '</table>';

 echo $product_list;