我在php工作,现在我正在应用while循环到我的代码。 我从数据库中获取数据。 现在我必须将该数据应用于页面中的一个Div。
我的问题是" div class =" item active"" 在循环中每次活动类都需要。现在我想改变它,就像在第一个循环过程后第二个开始时我想要将该div改为此" div class =" item"" 。
我在这个循环过程中没什么新意,所以我无法解决这个问题。需要帮忙。谢谢。
<?php
$sqlEvent = "SELECT * FROM eventdata WHERE id='$id'";
$resultEvent = mysqli_query($connection, $sqlEvent);
if (mysqli_num_rows($resultEvent) > 0) {
while ($rowEvent = mysqli_fetch_array($resultEvent)) {
?><div class="item active"> <img src="images/event/1.jpg" alt="..." class="img-responsive">
<div class="carousel-caption wedding-area">
<h2><?php echo $rowEvent['eventTitle']; ?></h2>
<h4><?php echo $rowEvent['eventDate']; ?></h4>
<h4><?php echo $rowEvent['eventTime']; ?></h4>
<div class="details hidden-xs">
<p><?php echo $rowEvent['eventDesc']; ?> </p>
</div>
<a href="#" class="btn btn-default" role="button">Read More</a> </div>
</div><?php
}
}
?>
答案 0 :(得分:1)
使用计数器检查第一次迭代
$i = 1;// initialized counter
while ($rowEvent = mysqli_fetch_array($resultEvent)) {
if ($i == 1) {// check for first iteration
?><div class="item active"> <img src="images/event/1.jpg" alt="..." class="img-responsive">
<?php } else { ?>
<div class="item"> <img src="images/event/1.jpg" alt="..." class="img-responsive">
<?php
}
$i++;// increase counter
?>
答案 1 :(得分:0)
使用pdo函数它们更容易使用
http://php.net/manual/pl/pdostatement.fetchall.php
并始终在sql查询中转义值!
<?php
$sth = $dbh->prepare("SELECT * FROM eventdata WHERE id=?);
$sth->execute([$id]);
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $i => $rowEvent) {
?><div class="item <?php if(1 === $i) echo 'active';?>"> <img src="images/event/1.jpg" alt="..." class="img-responsive">
<div class="carousel-caption wedding-area">
<h2><?php echo $rowEvent['eventTitle']; ?></h2>
<h4><?php echo $rowEvent['eventDate']; ?></h4>
<h4><?php echo $rowEvent['eventTime']; ?></h4>
<div class="details hidden-xs">
<p><?php echo $rowEvent['eventDesc']; ?> </p>
</div>
<a href="#" class="btn btn-default" role="button">Read More</a> </div>
</div><?php
}
?>
答案 2 :(得分:0)
你只希望循环的第一个div具有类“active”... 那么这段代码应该适合你
设置变量=“actìve”然后在body loop set =“”的末尾。
在每次迭代中,在div的class属性中打印变量
$sqlEvent = "SELECT * FROM eventdata WHERE id='$id'";
$resultEvent = mysqli_query($connection, $sqlEvent);
if (mysqli_num_rows($resultEvent) > 0) {
$classActive = "active";
while ($rowEvent = mysqli_fetch_array($resultEvent)) {
?>
<div class="item <?php echo $classActive; ?>">
<img src="images/event/1.jpg" alt="..." class="img-responsive">
<div class="carousel-caption wedding-area">
<h2><?php echo $rowEvent['eventTitle']; ?></h2>
<h4><?php echo $rowEvent['eventDate']; ?></h4>
<h4><?php echo $rowEvent['eventTime']; ?></h4>
<div class="details hidden-xs">
<p><?php echo $rowEvent['eventDesc']; ?> </p>
</div>
<a href="#" class="btn btn-default" role="button">Read More</a> </div>
</div>
<?php
$classActive = "";
}
}