Spud
Spud

Reputation: 371

Echo results of array while a certain condition exists

I have a query that is producing results:

SELECT 2article.idarticle, 2article.a_idcategory, 2article.a_name, 
2article.a_desc, 2article.a_content, 2article.a_featured, 2article.a_verified, 
2category.cat_name, 2file.file_name, 2file.file_desc, 2file.file_loc, 
2image.i_name, 2image.i_desc, 2image.i_loc, 2link.l_url, 2link.l_name, 2link.l_desc
FROM 2article
LEFT JOIN 2category on 2article.a_idcategory = 2category.idcategory
LEFT JOIN 2file ON 2article.a_idfile = 2file.idfile
LEFT JOIN 2image ON 2article.a_idimage = 2image.idimage
LEFT JOIN 2link ON 2article.a_idlink = 2link.idlink
$stmt->prepare($qry_art);
$result = $db->query($qry_art);
$row = $result->fetch_array();
$stmt->execute();

I would like to echo various results from this query where a particular condition exists. Something like this (it doesn't work, but I hope it will help explain what I want to do)

if(isset($row['a_idcategory']) && $row['a_idcategory'] = 9) do {
echo $row['a_name'].'<br>';
} while($row = $result->fetch_array());

In other words I only want $row['a_name'] to be echoed if/while corresponding $row['a_idcategory'] equals 9. So far, everything I've tried brings back all the 'a_name' results. I'm at a loss and I've tried many things. I'm not even sure if what I want to do is possible. Any help would be greatly appreciated. Cheers

Upvotes: 1

Views: 63

Answers (1)

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

Your if condition is wrong, and place if inside while loop.

if(isset($row['a_idcategory']) && $row['a_idcategory'] = 9)
                                                       ^

should be

while($row = $result->fetch_array()){
    if($row['a_idcategory'] == 9) {
        echo $row['a_name'].'<br>';
    } 
}

= is assignment operator == is comparison operator.

UPDATE

You can also use this filter in your sql query

....LEFT JOIN 2link ON 2article.a_idlink = 2link.idlink
WHERE 2article.a_idcategory = 9

Upvotes: 2

Related Questions