我正在尝试在HTML表格中显示具有特定类别的数据库中的所有产品。但是我不确定如何将表限制为三列。
这是我的代码:
<table>
<?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 catagory ' );
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$prodname = $row['prodname'];
$prodID = $row['prodID'];
if ($i % 5 == 0 || $i == 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 % 3 == 0 || $i == (mysql_num_rows($result)-1)) {
echo "</tr>";
}
}
?>
<table>
我正在等待在同一个“单元格”中显示prodID,prodtitle和image,但只有三列(每行三个产品)。
我该怎么做?
答案 0 :(得分:2)
echo "<tr>"; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$prodname = $row['prodname'];
$prodID = $row['prodID'];
echo "
<td>
<b>$prodname </b><br />
Product ID: $prodID<br />
<img src='/userpics/$prodID.jpg' height='200' width='200'>
</td>";
if ($i % 3 == 0) {
echo "</tr> <tr>"; // it's time no move to next row
}
}
echo "</tr>"; // last row ending
请注意,$ i现在从1开始,它在num_rows <=
时循环,而不是<
。
答案 1 :(得分:1)
这看起来不太好。
if ($i % 5 == 0 || $i == 0) {
我认为应该是
if ($i % 3 == 0 || $i == 0) {
否则当您关闭旧版<tr>
时,将不会打开新的echo "<table><tr>"; // Open the first row
for ($i ..... etc.) {
-- SNIP --
if ($i % 3 == 0) {
echo "</tr><tr>"; // imediately open new row
}
}
echo "</tr></table>"; // Close last row as well as table
。
扩展这一点,你可以让自己更轻松。
{{1}}
答案 2 :(得分:1)
<table>
<?php
$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");
$catagory = mysql_real_escape_string($_GET['q']); // prevent SQL injections
if(empty($catagory)) {
die('You need to enter a catagory');
}
$result = mysql_query("SELECT * FROM products WHERE catagory = '$catagory';") or die(mysql_error());
// a general error might have occurred,
// may or may not be related to not entering a catagory
$rows = mysql_num_rows($result); // cache the number for performance
for ($i = 0; $i < $rows; ++$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 % 3 === 0) {
echo "</tr>";
}
}
if($i % 3 > 0) {
// last row was not full
echo '</tr>';
}
?>
</table>