LightningWrist
LightningWrist

Reputation: 937

How do I add a limit to query results in a if statement?

I have a query I am using where I'm displaying the results in 3 different areas. One of the areas I want to not set a limit and two of them I want to limit them to one. I was thinking in the foreach of those specific two areas I could add the limits there. I'm just not sure how to do that, and if that's the best way.

Here is my query:

$comments_query = "SELECT * FROM airwaves_comments aw,users u WHERE u.id=aw.from_id AND aw.FROM_id=aw.to_id AND aw.from_id=".$profile_id." order by aw.created_on desc" ;

Here is are the results being displayed where I don't want a limit.

if ($airwave)
 {
 foreach ($airwave as $airwave_comment_row)
 {
// stuff
}
}

Here are the results being displayed where I want to limit to one:

if ($airwave && $profile_id == $session_id)
            {
                foreach ($airwave as $airwave_comment_row)
                {
                    echo "<div id='profile_airwave'>";
                    echo $airwave_comment_row['comment'];
                    echo "<br />";
                    echo "<span class='profile_airwave_info'>"; 
                    echo $airwave_comment_row['created_on'];
                    echo "</span>";
                    echo "</div>";
                }
}

Is this possible, for them to share the same query? Or do I have to write a new query?

thanks

Upvotes: 0

Views: 120

Answers (2)

Nisam
Nisam

Reputation: 2285

You can change your query like this,

$comments_query = "SELECT * FROM airwaves_comments aw,users u WHERE u.id=aw.from_id AND aw.FROM_id=aw.to_id AND aw.from_id=".$profile_id." order by aw.created_on desc" ;
if($profile_id == $session_id){
$comments_query .= " LIMIT 0,1"
}

OR You can try with the same logic you have

    if ($airwave && $profile_id == $session_id)
         $airwave_comment_row = $airwave[0];
         // takes the first row
    }else if($airwave){
    foreach ($airwave as $airwave_comment_row)
       {
        // stuff
       }
   }

Upvotes: 1

Anthony Sterling
Anthony Sterling

Reputation: 2441

I think you can do with with a UNION query, but you would need to check if that's the best approach - if it works.

I would check, but I don'y have access to a MySQL server at present.

(SELECT * FROM table WHERE category = 1)
UNION
(SELECT * FROM table WHERE category = 2 LIMIT 10)
UNION
(SELECT * FROM table WHERE category = 3)

Anthony.

Upvotes: 0

Related Questions