Mat*_*idd 2 html php if-statement html-table
我正在开展一项小型大学任务,使用PHP为网站构建一个简单的电子商务引擎.
我目前有以下脚本设置来显示一个类别中的产品,所有这些都是从MySQL数据库中检索的.
http://example.com/category.php?id=2
Run Code Online (Sandbox Code Playgroud)
我目前遇到的问题是,对于显示的每个产品,脚本只是简单地将每个产品并排回到新的表条目中.这导致它们跨越页面而不是垂直.
改变此代码的最佳方法是,每行最多包含三个产品?If循环或沿着这些线的东西?非常感谢支持!
<?php
//Create Session
session_start();
//Connect to database
include "conn.php";
//Retrieve Header
include "header.php";
//Get Category ID
if (isset($_GET['id'])){
$CategoryID = $_GET['id'];
//QUERY collects product name, and product ID.
$q="SELECT ProductID, ProductName, Price,img FROM Products WHERE CategoryID=$CategoryID";
//QUERY collects Product Category descriptions
$d="SELECT `Desc` FROM ProductCategories WHERE CategoryID=$CategoryID";
//retrive and execute SQL query results and save into a variable
$result = mysqli_query($_SESSION['conn'],$q);
$result2 = mysqli_query($_SESSION['conn'],$d) or die(mysql_error());
//Retrieve Product Category Description
echo "<div>";
while ($myResult = mysqli_fetch_row($result2)){ //Create an array
echo "<p>".$myResult[0]."</p>";
}
echo "</div>";
//Retrieve Products in category
echo "<div align='center'><table border='1px' bordercolor='#000000' width='200px'><tr>"; //Define table, row and div containing each product
while ($row = mysqli_fetch_row($result)){ //Create an array
echo "<td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td>"; //Close table cell
}
echo "</tr></table></div>";//Close table, div and row
mysqli_free_result($result);
}
// Retireve Footer
include "footer.php";
?>
Run Code Online (Sandbox Code Playgroud)
在涉及任何类型的编程时,我是新手,所以我将感谢您的耐心/任何支持.此外,我知道SQL注入问题,并将在以后修复此问题.
那么你会用计数器跟踪你的迭代次数,然后每次你点击$counter%3 === 0
(用你想要的每行替换3)你将关闭tr
并开始一个新的:
$counter = 0;
$perRow = 3;
while ($row = mysqli_fetch_row($result)){ //Create an array
if($counter === 0) {
echo '<tr>';
} else if ($counter%$perRow === 0 ) {
echo '</tr><tr>';
}
echo "<td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td>";
$counter++;
}
Run Code Online (Sandbox Code Playgroud)