Jump to content

multiple conditions in a while loop


Recommended Posts

Been at it a while now and the scripts like pretty big haha.

 

But I need to know a way to get either to conditions into a while (here ){loop}

 

Because what I've got so far is a while loop to do the initial loop ( creates a table with a div and some javascript with "subcatagories")

And I've got a second loop in there which ( as the loop continues ) loops through to grab the "subcatagories" data. But I have an if statement that requires three arguments and I've tried putting two conditions into the while (brackets).

 

Heres the segment of code I'm working on.

 

        function catagories_fetch(){ //Fetch Catagories
            
            $cfmain = mysql_query(
            "SELECT *  
            FROM catagories
		WHERE ismain='1'
            ORDER BY ID DESC")
            or die(mysql_error());
            
             $cfmain2 = mysql_query(
            "SELECT *  
            FROM catagories
            WHERE ismain='1'
            ORDER BY ID DESC")
            or die(mysql_error());

		$cfsub = mysql_query(
            "SELECT *  
            FROM catagories
		WHERE issub='1'
            ORDER BY ID DESC")
            or die(mysql_error());
            
		while($cff = mysql_fetch_array($cfmain)){
                               
                 echo '<table width="680" border="0" cellspacing="0" cellpadding="0">';
                                   
                 if($cff['ismain'] = '1' && $cff['active'] = '1'){
                  
                     echo '<tr><td class="browse">';
                     echo '<a href="javascript:collapse' . $cff['ID'] . '.slideit()" class="productheaders">' .str_replace("_", " ", $cff["catagory"]) . '</a>';
                     echo '</td></tr>';
                     //End Row 1
                     echo "<tr><td><div class='catagorydivs' id='catagorydivs" . $cff['ID'] ."' onmouseover=style.backgroundColor='#ECE0ED' onmouseout=style.backgroundColor='#FFFFFF'>";
                     
                     echo "<table width='100%'>";
                     echo '<tr><td class="maintxt"><strong>' . $cff['dblurb'] . '</strong></td></tr><tr><td></td> </tr>';

                     while ($cfsubf = mysql_fetch_array($cfsub) && $cff1 = mysql_fetch_array($cfmain2)){
                                              
                     if($cfsubf['issub2main'] = $cff1['catagory'] && $cfsubf['active'] = '1'){
                         
                         echo "blah test" . $cfsubf['catagory'];
                         
                        echo '<tr><td>
                        <a class="maintxt" href="http://new.noirorchidemporium.co.uk/Iframes/products/catagories/?paction=prod_list_pc&catagory=' . $cfsubf['catagory'] . '">' . $cfsubf['catagory'] . ' --></a></td></tr>';
                        
                     }//End IF issub check
                     
                  }//End contained WHILE
                  
                     echo '<tr><td> </td></tr>';
                     echo '</table>';                
                     
                     echo '</div></td></tr>';
                 
                                   
                 }//End IF ismain check

            echo '<tr><td> </td></tr>';
            //End Row 2     
            echo '</table>';
            echo '<script type="text/javascript">
//Syntax: var uniquevar=new animatedcollapse("DIV_id", animatetime_milisec, enablepersist(true/fase), [initialstate] )
var collapse' . $cff['ID'] . ' = new animatedcollapse("catagorydivs' . $cff['ID'] .'", 400, false, [close])</script>';            
            }//End while
            
        }//End catagories_fetch()

 

sorry about its length but thats the whole function ( in my class ). And just incase its not clear enough I need that contained while loop to be able to give me two differant $variable['arrays']; or how do I get the first loops variable because it doesnt seem to want to find it ( $cff['catagory']; ) tried that it doesnt work at all.

Link to comment
Share on other sites

I really can't understand what you are asking, but this might be the cause of at least one problem; You are using the equals assignment operator where I think you want to be using the comparison one, on this line:

if($cfsubf['issub2main'] = $cff1['catagory'] && $cfsubf['active'] = '1'){

Link to comment
Share on other sites

I wasnt sure of it. I tried to make it clear ( I jsut suck at asking for stuff ;[ )

 

I need the contained loop to have two differant variables in it that I can use if you look theres one variable $cff['array']; and $cfsubf['array']; I need both for the contained while loop because I cant seem to compare two values like before I put the loop in there. Not sure if I've explained it any better.

 

But the if statements alright it worked before I put the loop in there its just the && $cff1 = mysql_fetch_array(blah blah) bit that doesnt work I debugged it by echoing ( or trying ) both values and only the first condition was working.

 

Below is a link to the page that I'm working on

 

http://new.noirorchidemporium.co.uk/Iframes/products/catagories/?paction=catagories

 

Click on the purple bar.

 

I'll explain it lol. The purple bar is the echo from the first while loop. you click it and it drops down and then shows you a load of links inside it. Which is where I'm stuck because this requires two variables to compare one against the other to make sure that the sub catagory belongs to that main catagory.

 

GOD I really suck at explaining stuff sorry guys I try my best  ;)

Link to comment
Share on other sites

Are you trying to compare the variable $cfsubf['issub2main'] to $cff1['catagory'] or are you trying to set them equal to eachother? If it is the latter, you're fine, but otherwise you need to use the comparison operator.

 

And I still am not entirely sure what you mean by "I need the contained loop to have two differant variables in it." Why can't you? Could you maybe make a smaller concept snippet of code to show what you are trying to do?

Link to comment
Share on other sites

I'll try explaining with steps lol ::)

 

1. Queries are set to a variables ( top of function )

 

2. Initial while loop is initialized with the parameter ($cff = mysql_fetch_array($cfmain)

 

3. Few echos for layout and JS

 

4. Contained while loop is initialized with the aim to retrieve the sub catagories information.

 

5. if statement that determines what parent the sub catagory is a child to and checks whether its an active subcatagory

 

6. contained loop echos all child sub catagories inside the parents table.

 

Its steps 4 to 6 I'm stuck with I've managed to here but I cant work out how to get the comparison to work.

 

The current if statement

 

if($cfsubf['issub2main'] = $cff1['catagory'] && $cfsubf['active'] = '1'){

some code

}

 

Works fine its the two mysql_fetch_arrays I'm having trouble with I need them both to be avaliable in the same loop to extract two differant data sets to compare them.

 

Sorry if this still doesnt explain it I'm stumped at even explaining the damn thing hahahaha

Link to comment
Share on other sites

I think you are going about this the wrong way. Instead of querying for all the information and then checking if it is right, you should be putting the conditions in the query so that your result set that is returned doesn't need to be looped through multiple times. If you show how your tables are set up I can try to help you come up with a query.

 

Aside from that, like I said before, you're if statements don't work. You are using the assignment operator (=) instead of the comparison operator (==). This means that your if statements like, "if($cff['ismain'] = '1' && $cff['active'] = '1')" simply set the variables $cff['ismain'] and $cff['active'] equal to 1 and the if statement actually evaluates like this: "if(true && true)." This means it will never be false. To go along with that, your query checks for "ismain" to be 1, so it will always be 1 anyway, which means that if statement is unnecessary and would have always evaluated to true, anyway.

Link to comment
Share on other sites

The IF clause isnt for checking if its set to true or not. Its comparing two differant database values against each other

 

so for example the first loop pulls all the data for a main catagory the second loop goes through the database looking for any records with a subcatagoryto with the same value as the name of the main catagory.

 

 

so

 

if(subcatagory to is the same as maincatagory and active){

loops for all values the same.

}

 

:P

 

hopefully someone will understand me....  ???

Link to comment
Share on other sites

The IF clause isnt for checking if its set to true or not. Its comparing two differant database values against each other

I get the feeling that you aren't fully reading my posts; that if statement is wrong and I explained why.

 

As discomatt said, and as I said already, if you would show how your tables are set up I can help you do what you are trying to do.

Link to comment
Share on other sites

Hey sorry guys, having a real rough week.

 

I've got one problem sorted but theres another minor that I think I can sort but I guess its worth asking :)

 

The table structure is:

 

CREATE TABLE catagories (
  ID tinyint(4) NOT NULL auto_increment,
  catagory text NOT NULL,
  active int(1) default '0',
  ismain int(1) default '0',
  issub int(1) default '0',
  dblurb text NOT NULL,
  issub2main text NOT NULL,
  PRIMARY KEY  (ID)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
*
*
*
INSERT INTO catagories VALUES (1,'Wierd_And_Wonderful',1,1,0,'Want something a little different as a gift or a treat?....look no further. ','');
INSERT INTO catagories VALUES (2,'Apothercary',1,1,0,'Hand-made in England, tested on humans, all natural, aromatherapy based lotions and potions','');

 

Thats the main catagory table

 

CREATE TABLE subcatagories (
  ID tinyint(4) NOT NULL auto_increment,
  catagory text NOT NULL,
  active int(1) NOT NULL default '0',
  issub2main text NOT NULL,
  PRIMARY KEY  (ID)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

*
*
*
INSERT INTO subcatagories VALUES (1,'Magic_Supplies',1,'Wierd_And_Wonderful');
INSERT INTO subcatagories VALUES (2,'Chakra',1,'Wierd_And_Wonderful');
INSERT INTO subcatagories VALUES (3,'Gift_Bags',1,'Apothercary');
INSERT INTO subcatagories VALUES (4,'Massage_Oils',1,'Apothercary');

 

And thats the sub catagory table.

 

And basically I'm having trouble with the loop itself it doesnt seem to loop for the second catagory I'm still toying with it.

 

http://new.noirorchidemporium.co.uk/Iframes/products/catagories/

 

If you click and see guys heres a snippet of the class sorry its so long :[

 

function catagories_fetch(){ //Fetch Catagories
            
            $cfmain = mysql_query(
            "SELECT *  
            FROM catagories
		WHERE ismain='1'
            ORDER BY ID DESC")
            or die(mysql_error());
            
             $cfsub = mysql_query(
            "SELECT *  
            FROM subcatagories
            ORDER BY ID DESC")
            or die(mysql_error());
            
            echo '<div id="prd">';

		while($cff = mysql_fetch_array($cfmain)){
                echo '<table width="680" border="0" cellspacing="0" cellpadding="0">';
                  
                     echo '<tr><td class="browse">';
                     echo '<a href="javascript:collapse' . $cff['ID'] . '.slideit()" class="productheaders">' . str_replace("_", " ", $cff["catagory"]) . '</a>';
                     echo '</td></tr>';
                     //End Row 1
                     echo "<tr><td><div class='catagorydivs' id='catagorydivs" . $cff['ID'] ."' onmouseover=style.backgroundColor='#ECE0ED' onmouseout=style.backgroundColor='#FFFFFF'>";
                     
                     echo "<table width='100%'>";
                     echo '<tr><td class="maintxt"><strong>' . $cff['dblurb'] . '</strong></td></tr><tr><td></td> </tr>';

                     while ($cfsubf = mysql_fetch_array($cfsub)){

                     if($cfsubf['issub2main'] == $cff['catagory']
                     &&
                     $cfsubf['active'] = '1'){
                         
                        echo '<tr><td>
                        <a class="maintxt" href="http://new.noirorchidemporium.co.uk/Iframes/products/catagories/?paction=prod_list_pc&catagory=' . $cfsubf['catagory'] . '">' . $cfsubf['catagory'] . ' --></a></td></tr>';
                        
                     }//End IF issub check
                     
                  }//End contained WHILE
                  
                     echo '<tr><td> </td></tr>';
                     echo '</table>';                
                     
                     echo '</div></td></tr>';
                     
            echo '<tr><td> </td></tr>';
            //End Row 2     
            echo '</table>';
            echo '<script type="text/javascript">
//Syntax: var uniquevar=new animatedcollapse("DIV_id", animatetime_milisec, enablepersist(true/fase), [initialstate] )
var collapse' . $cff['ID'] . ' = new animatedcollapse("catagorydivs' . $cff['ID'] .'", 400, false, [close])</script>';
            
            }//End while
            
            echo "</div>";
            
        }//End catagories_fetch()

 

again apologies for my impatience before...

Link to comment
Share on other sites

I don't know how maleable your project is, but your tables seem kind of inefficient for what they are. I would suggest using a format like this:

categories(CatID,Name);

subcategories(SubCatID, Name, CatID);

 

If you have something like that, you can use the simple query:

"SELECT * FROM subcategories s LEFT JOIN categories c ON c.CatID = s.CatID"

 

I'd like to help you make a more efficient query for your current tables, but I am not quite clear as to how you are relating the sub categories with thier super categories. Is every category in the category table, and then sub categories are duplicated in the subcategories table?

Link to comment
Share on other sites

There are two tables ( only as of tonight actually ) one which contains main catagories ( so Wierd_And_Wonderful and Apothercary )

 

And then theres a second table for sub catagories the link is in the sub catagories table in the column issub2main ( linking it with the main catagories name ) if you get me.

 

really it needs to be done in a way I can compare the issub2main with the main catagories name and check if its active.

Link to comment
Share on other sites

So issub2main is the foreign key to category in the categories table? In that case, this query should work:

"SELECT * FROM subcategories s LEFT JOIN categories c ON c.category = s.issub2main"

 

That query will give you each sub category with its respective super category in the same row so you don't need to tier loops.

Link to comment
Share on other sites

Not sure because I need to loop it anyway because inside the loop I found before, that the "parent" loop was only bringing back one sub cat hence the second loop inside.

 

with the current code I get one main cat appear with all the appropriate sub catagories but the second doesnt as if the loop breaks the second time round.

 

If you could tell me how to use this query effectivly ( I'm not a PHP/MySQL magician just yet  ;) )

 

Thanks though  :)

Link to comment
Share on other sites

Well this is all you have to do to get all of the sub categories and their super categories with my query:

<?php
$qry = mysql_query("SELECT s.category as subcat, c.category as cat FROM subcategories s LEFT JOIN categories c ON c.category = s.issub2main") or die(mysql_error());
while ($row = mysql_fetch_assoc($qry))
   echo $row['subcat'] . " from " . $row['cat'] . "<br>";
?>

 

When code that is the size of what you posted can be replaced with this, it makes me hesitant to try to figure out how to make yours work. If you would try this first I think it would be a lot easier for you.

Link to comment
Share on other sites

Yeah as I said I'm no wizzard with it yet  ;) but I'm learning

 

http://new.noirorchidemporium.co.uk/testhelp.php

 

I get that but I'm a little bewildered as to how I get this into my function and achieve the same results I'm going to have to toy with it tomorrow after work but yeah little stumped. Thank you loads though!  ;D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.