1

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

4 Answers 4

3

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".

Sign up to request clarification or add additional context in comments.

Comments

2

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
}

1 Comment

That actually works perfectly, thanks. I never know you could subtract using -- either, that's new to me
1

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

Comments

-1

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
}

2 Comments

Thanks, how would I put that in an example as I have just put in my question?
In that case you have to replace the count($resultList) in my code with a call to mysql_num_rows($query), and place it in the else part of your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.