PHP数组导致HTML表格

时间:2013-08-02 09:57:36

标签: php html mysql arrays

我正在尝试将MYSQL数据库中的结果数组转换为html表,但是当我这样做时,它似乎每行显示一个项目(1列)

这是我的代码

<?php 

$catagory=$_GET["q"];

$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con) 
  {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("cl49-XXX", $con)or die( "Unable to select database");

$result=mysql_query("SELECT * FROM products WHERE catagory  = '$catagory' ")or die('You need enter a catagoryE ' );
while($row = mysql_fetch_array($result)) {
  $prodname=$row['prodname'];
  $prodID=$row['prodID'];
  echo"
  <table>
  <tr>
  <td>
  <b>$prodname </b><br>
  Product ID: $prodID<br /> 
 <img src='userpics/$prodID.jpg' height='200' width='200'></td></table> ";
}
?>

我想要一个包含3列而不是1列的表?

4 个答案:

答案 0 :(得分:0)

你应该创建3列。

您只创建了一列,您的代码稍作清理:

 <table>
   <tr>
     <td>
       <b>$prodname </b><br>Product ID: $prodID<br/><img src='userpics/$prodID.jpg' height='200' width='200'>
    </td>
   </tr>
  </table>

如何创建3?

     <table>
      <tr>
        <td>This is a column</td>
        <td>This is a column</td> 
        <td>This is a column</td>
      </tr>
     </table>

答案 1 :(得分:0)

用此

替换您的while循环
?>
<table>
    <?php
    while($row = mysql_fetch_array($result))
    {
        $prodname = $row['prodname'];
        $prodID = $row['prodID'];
        echo "
        <tr>
            <td><b>$prodname </b></td>
            <td>Product ID: $prodID</td>
            <td><img src='userpics/$prodID.jpg' height='200' width='200'></td>
        </tr>";
    }
    ?>
<table>

然后阅读html表如何工作

<强>更新 做你想要的是一个非常奇怪的方式来使用一个表,但是如果这是你想要的,这样的东西应该工作;

?>
<table>
    <?php
    for ($i = 0; $i < mysql_num_rows($result); $i++)
    {
        $row = mysql_fetch_array($result);

        $prodname = $row['prodname'];
        $prodID = $row['prodID'];
        if ($i % 3 == 0) {
            echo "<tr>";
        }
        echo "
        <td>
            <b>$prodname </b><br />
            Product ID: $prodID<br />
            <img src='userpics/$prodID.jpg' height='200' width='200'>
        </td>";

        if (($i + 1) % 3 == 0 || ($i + 1) == mysql_num_rows($result)) {
            echo "</tr>";
        }
    }
    ?>
<table>

这应该每行产生3列,如果你想要更多,在两次出现时将$i % 3 == 0更改为$i % 4 == 0

答案 2 :(得分:0)

您需要编辑以下代码:

  <table>
     <tr>
      <th>Name</th>
      <th>Id</th>
      <th>Img</th>
   </tr>
 <?php 
 while($row = mysql_fetch_array($result)) {
     $prodname=$row['prodname'];
      $prodID=$row['prodID'];
     echo"
  <tr>
      <td>$prodname </td>
      <td> $prodID</td> 
     <td><img src='userpics/$prodID.jpg' height='200' width='200'>
      </td></tr> ";
 }?>

答案 3 :(得分:0)

您需要在PHP echo中创建三列:

<table>
<tr>
<td>
<b>$prodname</b></td>
<td>Product ID: $prodID</td> 
<td><img src='userpics/$prodID.jpg' height='200' width='200'></td>
</table>