在两列中显示数据库的结果

时间:2012-04-17 01:42:18

标签: php

编辑:这就是我想要实现的目标:http://i.imgur.com/KE9xx.png

我试图在两列中显示数据库中的结果。我对PHP有点新意,所以我对如何做到这一点没有丝毫的线索。任何人都可以帮我吗?提前谢谢。

这是我目前的代码:

include('connect.db.php'); 
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
  // display records if there are records to display
  if ($result->num_rows > 0)
  { 
    // display records in a table
    echo "<table width='415' cellpadding='0' cellspacing='0'>";
    // set table headers
    echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
        <td><img src='media/title_status.png' alt='Status'/></td>
      </tr>";
    echo "<tr>
        <td><div class='tpush'></div></td>
        <td>&nbsp;</td>
      </tr>"
    while ($row = $result->fetch_object())
    {
      echo "<tr>";
      echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
      echo "<td>" . $row->priority . "</td>";
      echo "</tr>";
    }
    echo "</table>";
  }
  // if there are no records in the database, display an alert message
  else
  {
    echo "No results to display!";
  }
}
// show an error if there is an issue with the database query
else
{
   echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();

3 个答案:

答案 0 :(得分:1)

一个好主意是将数据存储到一个简单的数组中,然后将它们显示在一个2-columned表中,如下所示:

$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);

$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;

// Put results in an array
while($r = mysql_fetch_assoc($query)) {
    $rows[] = $r;
    $i++;
}

//display results in a table of 2 columns

echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";

mysql_close($con);

答案 1 :(得分:0)

<table>
  <tr>
    <td>ProjectName</td>
    <td>Status</td>
    <td>ProjectName</td>
    <td>Status</td>
  </tr>
  <?php
     while($row = $result->fetch_object()) {
        echo "<tr>";
        echo "<td>".$row->ProjectName."</td>";
        echo "<td>".$row->Status."</td>";
        echo "<td>".$row->ProjectName."</td>";
        echo "<td>".$row->Status."</td>";      
        echo "</tr>";
     }
  ?>
</table>

这是图片中的事情。使用CSS,您可以操作tds。

答案 2 :(得分:0)

您的功能应该与此类似:

$query = "SELECT *
         FROM todo 
         ORDER BY id";
$result = $mysqli->query($query);

while($row = $result -> fetch_array()) {
   $feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;

然后,在您的HTML中已经设置了<table>,并且您通常会在其中插入<td><tr> put <?php echo $feedback?>(其中$ feedback是假定变量on从页面检索$反馈的HTML页面。这不是一个完整的修复程序,您的代码很难阅读,但从这里开始,您应该能够继续填写表格所需的所有额外信息,包括CSS。