Dylan Cross
Dylan Cross

Reputation: 5986

MYSQL PHP while loop, do something if there aren't a given amount of rows returned

I'm trying to figure out the best way to do something like this. Basically what I want to do (in a simple example) would be query the database and return the 3 rows, however if there aren't 3 rows, say there are 0, 1, or 2, then I want to put other data in place of the missing rows.

Say my query returns 2 rows. Then there should be 1 list element returned with other data.

Something like this: http://i42.tinypic.com/30xhi1f.png

$query = mysql_query("SELECT * FROM posts LIMIT 3");
while($row = mysql_fetch_array($query))
{
  print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else
{
  print "<li>Add something here</li>";
}

Upvotes: 1

Views: 306

Answers (4)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

If you dont find a row, Add extra information accordingly.

$query = mysql_query("SELECT * FROM posts");
for($i=0;$i<3;$i++){
    $row = mysql_fetch_array($query);
    if($row){
        print "<li>".$row['post']."</li>";
    }
    //(this is just to give an idea of what i would likkeee to be able to do
    else{
        print "<li>Add something here</li>";
    }
}

Upvotes: 1

Umbrella
Umbrella

Reputation: 4788

There are three ways I can think of, get the row count with mysql_num_rows, prime an array with three values and replace them as you loop the result set, or count down from three as your work, and finish the count with a second loop, like this:

$result = db_query($query);
$addRows = 3;
while ($row = mysql_fetch_assoc($result){
    $addRows--;
    // do your stuff
}
while ($addRows-- > 0) {
    // do your replacement stuff
}

Upvotes: 2

fivedigit
fivedigit

Reputation: 18682

Assuming you store the rows in an array or somesuch, you can simply do some padding with a while loop (depending how you generate the other data):

while (count($resultList) < 3) {
    // add another row
}

Upvotes: -1

TimWolla
TimWolla

Reputation: 32701

You can get the number of items in the resultset with mysql_num_rows. Just build the difference to find out how many items are "missing".

Upvotes: 3

Related Questions