If fetched data from MySql is smaller than *number*, show this, else show something else?

StackOverflow https://stackoverflow.com/questions/1427323

  •  07-07-2019
  •  | 
  •  

Question

Hi Masters of Web Programing. I've got this code:

<?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>

As we can see, the number of fetched rows are limited to 36. How to make if rows are smaller than 36, to show the existing ones plus adding something else for each one until 36? For example this is a script for pixel advertisement, and I want to visualize the existing pixels (for example, I have 20 inserted pixels), and to show empty boxes into other places that are empty (total 36 places - 20 already placed items = 16 empty places) until the count reaches total 36 boxes.

As you can see, I tried with "If", "else", but it always shows only empty boxes (becouse I don't know how to tell it to show RESULTS + empty boxes)...

Was it helpful?

Solution

Rewrite everything into a for loop, it also makes everything a bit easier to understand:

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>";
    }
}

This will always iterate through the loop 36 times, those times it will find a row it will print the row, otherwise it will print the empty banner tag.

OTHER TIPS

Use mysql_num_rows:

if (mysql_num_rows($res) >= 36) {
    // ...
}

Have you tested the code that executes if the if statement is true?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top