我正在尝试整理我的产品,我使用下面显示的php代码从我的产品数据库中检索到了这些产品,我遇到的问题是这些产品是一个接一个地垂直列出的,我希望它们并排显示,例如,水平显示4个产品及其价格、下面的描述,我确实尝试过通过提供类ID来使用CSS对其进行样式化,但我无法对其进行排序,我也在这里进行了搜索,但没有成功。如有任何帮助,将不胜感激
<?php
$con = mysqli_connect("localhost", "root", "pass", "sharifstores");
$result = mysqli_query($con, "SELECT * FROM tblProduct");
echo "<br>";
echo "<table>";
while ($row = mysqli_fetch_array($result)) {
$pname = $row[1];
$image = $row[2];
$description=$row[3];
$price = $row[4];
echo "<tr><td>$pname</td>";
echo "<td><img src='"$image'" width='"200'" height='"180'" /> </td>";
echo "<tr><td>$description</td>";
echo "<tr><td>$price</td>";
echo "<td><form action='"basket.php'" method='"POST'">"
. "<input type='"submit'" name='"$pname'" value='"Add $pname to Basket'" />"
. "</form></td></tr>";
}
echo "</table>";
mysqli_close($con);
?>
您可以这样做:首先遍历行以获取所有数据。然后再次循环显示它们。
$products = array();
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$product = new stdClass();
$product->name = $row[1];
$product->description = $row[2];
$product->price = $row[3];
$product->price = $row[4];
$products[$i++] = $product;
}
echo "<tr>";
foreach($products as $product){
echo "<td>
$product->name
</td>";
}
echo "</tr>";
你基本上可以对每一个产品功能都这样做。有点跛脚,但它有效。
尝试此
<?php
$con = mysqli_connect("localhost", "root", "pass", "sharifstores");
$result = mysqli_query($con, "SELECT * FROM tblProduct");
echo "<br>";
echo "<table>";
while ($row = mysqli_fetch_array($result)) {
$pname = $row[1];
$image = $row[2];
$description=$row[3];
$price = $row[4];
echo '<div style="float:left; width:23%;margin:5px;">';
echo "<tr><td>$pname</td>";
echo "<td><img src='"$image'" width='"200'" height='"180'" /> </td>";
echo "<tr><td>$description</td>";
echo "<tr><td>$price</td>";
echo "<td><form action='"basket.php'" method='"POST'">"
. "<input type='"submit'" name='"$pname'" value='"Add $pname to Basket'" />"
. "</form></td></tr>";
echo "</div>";
}
echo "</table>";
mysqli_close($con);
?>
<div style="clear:both;"></div>
还有另一种方法:
<br/>
<table>
<?php
$con = mysqli_connect("localhost", "root", "pass", "sharifstores");
$result = mysqli_query($con, "SELECT * FROM tblProduct");
while ($row = mysqli_fetch_array($result)) {
$pname[] = $row[1];
$image[] = $row[2];
$description[] = $row[3];
$price[] = $row[4];
}
foreach($pname as $key => $name) { ?>
<div style="float:left; width:23%;margin:5px;">
<tr>
<td><?php echo $name; ?></td>
<td><img src="<?php echo $image[$key]; ?>" width="200" height="180" /></td>
<tr><td><?php echo $description[$key]; ?></td>
<tr><td><?php echo $price[$key]; ?></td>
<td>
<form action="basket.php" method="POST">
<input type="submit" name="<?php echo $name; ?>" value="Add <?php echo $name; ?> to Basket" />
</form>
</td>
</tr>
</div>
<?php } mysqli_close($con); ?>
</table>
<div style="clear:both;"></div>