我在php中编写一个网页,从mySQL数据库中检索玩家详细信息并将其写入div中的正文,例如:
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
我想要做的是将其中三个一次放入一个div中,这样当从数据库中检索到另外两个时,它将结束包含div并为接下来的三个开始一个新的,如下所示:
<div class="container">
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
<div class="infoDiv">
<img style="margin: 10px; float:left" src="epoch.png>
<p>Player Name: Kez</p>
<p>Player ID: 98723947923749333432</p>
<p>Player Morality: 0</p>
<p>Gender: Male</p>
</div>
</div>
。我用来将数据写入文档的php在这里:
$con = mysqli_connect($servername, $username, $password, $dbname);
$sql="SELECT PlayerName,PlayerUID,PlayerMorality,PlayerSex FROM player_data";
if ($result=mysqli_query($con,$sql)){
while ($row=mysqli_fetch_row($result)){
echo "<div class=\"infoDiv\">";
echo "<img style=\"margin: 10px; float:left\" src=\"epoch.png\"/>";
echo "<p>Player Name: " . $row[0] . "</p>";
echo "<p>Player ID: " . $row[1] . "</p>";
echo "<p>Player Morality: " . $row[2] . "</p>";
if($row[3]=="0"){
echo "<p>Gender: Male</p>";
}
else{
echo "<p>Gender: Female</p>";
}
echo "</div><br>";
}
mysqli_free_result($result);
}
我提前为这个问题道歉,我知道这个措辞很差,如果你不明白我在问什么,请随意问。感谢。
答案 0 :(得分:2)
只需保留一个柜台:
$rows_output = 0;
while(... fetch from db ...) {
if ($rows_output % 3 == 0) {
... start a new container ...
}
... output row data
if ($rows_output % 3 == 2) {
... just output the 3rd row, end the container ...
}
$rows_output++;
}
答案 1 :(得分:0)
最简单的解决方案是在循环中放置某种索引计数器,当它可以除以3时,你可以关闭当前div并开始新的:
$con = mysqli_connect($servername, $username, $password, $dbname);
$sql="SELECT PlayerName,PlayerUID,PlayerMorality,PlayerSex FROM player_data";
$resultIndex = 1;
if ($result=mysqli_query($con,$sql)){
while ($row=mysqli_fetch_row($result)){
echo "<div class=\"infoDiv\">";
echo "<img style=\"margin: 10px; float:left\" src=\"epoch.png\"/>";
echo "<p>Player Name: " . $row[0] . "</p>";
echo "<p>Player ID: " . $row[1] . "</p>";
echo "<p>Player Morality: " . $row[2] . "</p>";
if($row[3]=="0"){
echo "<p>Gender: Male</p>";
}
else{
echo "<p>Gender: Female</p>";
}
echo "</div><br>";
if ($resultIndex % 3 == 0) {
echo "</div><div class=\"container\">";
}
$resultIndex++;
}
mysqli_free_result($result);
}
答案 2 :(得分:0)
您可以使用array_chunk($array , how many per each)
并将其放在foreach
循环中,如
foreach (array_chunk($array , 3) as $row)
{
foreach ($row as $item)
{
the html goes here
}
// now 3 items has passed ,add something b4 the next 3
}