代码之家  ›  专栏  ›  技术社区  ›  Spoonk

如果从MySQL中获取的数据小于*数字*,则显示该值,否则显示其他值?

  •  0
  • Spoonk  · 技术社区  · 16 年前

    嗨,网络编程大师。 我有这个密码:

    <?PHP
    
    $db_user = 'user';
    $db_pass = 'password';
    $db_name = 'dbname';
    $db_host = 'localhost';
    if(mysql_connect($db_host,$db_user,$db_pass)) {
        mysql_select_db($db_name);
        mysql_query("CREATE TABLE IF NOT EXISTS smsads(id bigint unsigned primary key auto_increment, link varchar(255), fromnum varchar(60))");
        $res = mysql_query("SELECT * FROM smsads ORDER BY id DESC LIMIT 36");
        while($row = mysql_fetch_object($res)) {
    
            if ($res>=36){
    
            $http_link = $row->link;
            $root_link = strpos($http_link, '/');
                if ($root_link !== false) {
                $before = substr($http_link, 0, $root_link);
            }
    
            echo "<div id=\"banner\"><a href=\"http://{$before}\" alt=\"{$before}\" title=\"{$before}\" target=\"_blank\"><img src=\"http://{$http_link}\" /></a></div>";
        }
            else {
                echo $res . "<div id=\"banner\"></div>";
            }
        }
    }
    ?>
    </div>
    

    如我们所见,提取的行数限制为36。如果行小于36,如何使其显示现有行,并为每一行添加其他内容,直到36? 例如,这是一个像素广告脚本,我想可视化现有像素(例如,我插入了20个像素),并将空框显示到其他空的地方(总共36个地方-20个已放置的项目=16个空的地方),直到计数达到36个框。

    如你所见,我尝试过“如果”,“否则”,但它总是只显示空框(因为我不知道如何告诉它显示结果+空框)。

    3 回复  |  直到 16 年前
        1
  •  2
  •   Jimmy Stenke    16 年前

    将所有内容重写为for循环,这也使所有内容更容易理解:

    for($cnt = 0; $cnt < 36; $cnt++){
        if($row = mysql_fetch_object($res)){
            // In here you should have the code for the boxes to be filled.
            $http_link = $row->link;
            $root_link = strpos($http_link, '/');
            if ($root_link !== false) {
                $before = substr($http_link, 0, $root_link);
            }
            echo "<div id=\"banner\"><a href=\"http://{$before}\" alt=\"{$before}\" title=\"{$before}\" target=\"_blank\"><img src=\"http://{$http_link}\" /></a></div>";
        }else{
            // In here you should have the code for the empty boxes
            echo "<div id=\"banner\"></div>";
        }
    }
    

    这将总是在循环中循环36次,那些时候它将找到一行,它将打印该行,否则它将打印空的横幅标记。

        2
  •  0
  •   Ignas R    16 年前

    使用 mysql_num_rows :

    if (mysql_num_rows($res) >= 36) {
        // ...
    }
    
        3
  •  0
  •   user173778    16 年前

    如果if语句为真,是否测试了执行的代码?