我知道有几个类似于这个的问题,我已经查看了它们,但我仍然无法修改我的功能以便工作。
所以我有这个函数getCar_2();在functions.php页面中。问题是它应该显示更多的汽车,因为我在数据库中有更多的汽车,但它只显示最后一个。与getCar_1()相同,这两个函数是相同的。
这是功能:
<?php
function getCar_2(){
global $connect;
$text = "";
$get_car_2 = "SELECT * FROM cars WHERE category_id=5";
$get_car_result_2 = mysqli_query($connect, $get_car_2) or die(mysqli_query());
while($row_car_2 = mysqli_fetch_array($get_car_result_2)){
$car_model_2 = $row_car_2['car_name'];
$car_image_2 = $row_car_2['car_image'];
if(isset($car_model_2) && isset($car_image_2)){
$text = "
<div id='' style='white-space:nowrap;'>
<p id='model' style='display:inline-block; margin-right:10px; margin-left:10px; padding-top:10px; position:relative; bottom:35px;'>$car_model_2</p></a>
<img src='administrator/images/$car_image_2' width='120' height='80' style='display: inline-block; box-shadow: 0 0 11px #000;'/><br>
</div>";
}
}
return $text;
}
?>
并显示在另一个页面上:
<?php
$car_1 = getCar_1();
$car_2 = getCar_2();
if(!empty($car_1) || !empty($car_2)){
?>
<div class="block">
<div class="up">
<div class="title"><h4>Cars</h4></div>
</div>
<div class="down">
<div class="column_1"><b><?php echo $car_1; ?></b></div>
<div class="column_2"><b><?php echo $car_2; ?></b></div>
</div>
</div>
<?php
}
?>
答案 0 :(得分:1)
您没有连接text
变量,因此在每次循环传递时,它只包含最后一个值。您应该使用连接运算符.=
而不是赋值运算符=
$text .= "
答案 1 :(得分:1)
在使用之前,您将覆盖之前的行值。看起来你想要将新的行结果附加到前一个,为此...只需要添加一行和一个句点......
$text =''; //define $text so you can append to it
if(isset($car_model_2) && isset($car_image_2)){
$text .= "
<div id='' style='white-space:nowrap;'>
......
请注意.=
将新结果附加到上一行。
以这种方式附加变量称为连接。
句点也用于连接字符串和变量以进行打印。 喜欢 。 。 。
echo '<div class="column_1"><b>'. $car_1.'</b></div>';