在从mysql表加载的图像之间插入随机代码

时间:2013-09-23 18:29:49

标签: php mysql

我有以下代码:

<?php

    mysql_connect("localhost","root","");
    mysql_select_db("bravo");
    $res=mysql_query("select * from coisas");

?>
<div>
<?php
    while ($row=mysql_fetch_array($res)) {

    echo "<img src=\"{$row['imagem']}\">";

    }
?>
</div>

我需要在图像之间的随机位置显示一个adsense代码,任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

在while中添加一些代码:

while ($row=mysql_fetch_array($res)) {
   echo "<img src=\"{$row['imagem']}\">";
   echo "--- adsense code here---";
}

将在每张图片后注入。

或者,如果你真的想把它放在完全随机的位置:

$chanceOfAdsense = 35; // 35% chance of adsense appearing between any given images

while ($row=mysql_fetch_array($res)) {
   echo "<img src=\"{$row['imagem']}\">";

   if (mt_rand(0,99) < $chanceOfAdsense) {
      echo "--- adsense code here---";
   }
}

答案 1 :(得分:0)

从while循环构建输出数组,然后计算其中的值数。使用count(array)使用rand()计算随机数,然后迭代输出数组,并在索引与随机数匹配时使用if语句。

<?php

    mysql_connect("localhost","root","");
    mysql_select_db("bravo");
    $res=mysql_query("select * from coisas");

?>
<div>
<?php
    $output_array = array();
    while ($row=mysql_fetch_array($res)) {

      $output_array[] = "<img src=\"{$row['imagem']}\">";

    }

    //If you want the image to appear closer to middle, use fractions of $output_array
    //EG: rand(count($output_array)/3, count($output_array)*2/3));
    $rand_key = rand(0, count($output_array)-1);

    foreach ($output_array as $key => $img) {
       if ($key == $rand_key) {
           //echo your adsense code
       }
       echo $img;
    }
?>
</div>