我想在我的网站上显示10个视频后添加一个脚本。但我不明白怎么用if条件。这是我的php代码,显示所有的视频从我的数据库。我想显示10个视频后,它显示这个脚本。
<script>
This may contain the code of chitika code.
<script>
这是PHP代码。
<section class="videos">
<?php while ($res=$stmt_today->fetch()) { ?>
<?php if ($res === NULL) { ?>
<section class="box">
<a href="" class="video-box">
<img src="" width="190" height="90" alt="">
</a>
<strong class="title"><a href="">Coming Soon</a></strong>
</section>
<?php } else {
$immg = basename($images);
$imagee = "img"."/".$immg; ?>
<section class="box" style="width:100%; padding-top:2px;">
<?php if($images!=''){?>
<a href="video.php?vid=<?php echo $video_id ?>" class="video-box">
<img src="<?php echo $imagee; ?>" width="190" height="90" alt="">
</a>
<?php } else {?>
<a style="margin-left:5px;"href="video.php?vid=<?php echo $video_id ?>" class="video-box">
<img src="http://img.youtube.com/vi/<?php echo $video_thumbnail; ?>/mqdefault.jpg" width="190" height="90" alt="">
</a>
<?php } ?>
</section> <hr>
<?php } ?>
<?php } ?>
</section>
在你的循环中,你只需要一个简单的条件和一个计数器。
这里有一个例子。这是一个使用while
循环运行12次的循环,就像你的代码一样。
$i
是一个递增变量($i++
在每个循环结束时增加它的值)。if语句说,如果$i
等于10,那么做一些事情。在本例中,它会返回"已到达的10条记录"。
确保当你首先定义计数器($i = 1
)时,它是在while循环开始之前。
<?php
$i = 1;
while ($i <= 12) {
echo "record $i<br/>";
if ($i == 10) {
echo "10 records reached<br/>";
}
$i++;
}
?>
所以将这个思维过程应用到你的代码中会是这样的:
<section class="videos">
<?php $i = 1; // This is where the counter is defined ?>
<?php while ($res=$stmt_today->fetch()) { ?>
<?php if ($res === NULL) { ?>
<section class="box">
<a href="" class="video-box">
<img src="" width="190" height="90" alt="">
</a>
<strong class="title"><a href="">Coming Soon</a></strong>
</section>
<?php } else {
$immg = basename($images);
$imagee = "img"."/".$immg; ?>
<section class="box" style="width:100%; padding-top:2px;">
<?php if($images!=''){?>
<a href="video.php?vid=<?php echo $video_id ?>" class="video-box">
<img src="<?php echo $imagee; ?>" width="190" height="90" alt="">
</a>
<?php } else {?>
<a style="margin-left:5px;"href="video.php?vid=<?php echo $video_id ?>" class="video-box">
<img src="http://img.youtube.com/vi/<?php echo $video_thumbnail; ?>/mqdefault.jpg" width="190" height="90" alt="">
</a>
<?php } ?>
</section><hr>
<?php } ?>
<?php if ($i == 10) { // This is the new condition ?>
<script>
This may contain the code of chitika code.
<script>
<?php } // condition ends here ?>
<?php $i++ // increment the counter ?>
<?php } ?>
</section>
如果你不想在计数中包含空值(你的"即将到来"视频),你可以简单地将计数器增量$i++
向上移动到你的条件的else { ... }
部分。
<?php if (res === NULL) {
...
} else {
...
$i++;
} ?>