Jump to content

two varible loop


erdem

Recommended Posts

Hi, I have a two different css class needs to be in loop.

 

its

<li class="top">Item1</li>
<li class="bottom">Item2</li>
<li class="top">Item3</li>
<li class="bottom">Item4</li>

 

I just can't do this with php.

 

Let's say I have 15 items they goes into this html tags with php using while loop from database.

 

    $sql = mysql_query("SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'");
        if($numrows = mysql_num_rows($sql)){
            while($ROW = mysql_fetch_array($sql)){
                
  
                $liclass = array('ac_menu-item', 'menu-item-last');
                               
                    $data .= t_MenuContent($ROW,$liclass);
                
            }

 

 

could you please help me how can I loop these two variables?

Link to comment
Share on other sites

I'm having trouble trying to figure out what exactly you are trying to do, your code is pretty broken, I will break it down:

 

1. I like to separate the SQL and mysql_query call into separate variables, makes for easier debugging.

 

$sql ="SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'";
$query = mysql_query($sql) or die($sql . "<br />" . mysql_error());

 

2. this line:

 

if($numrows = mysql_num_rows($sql)){

 

does nothing, as it will always equate to TRUE. What you should do is check to make sure that at least one row has been grabbed from the query. e.g

 

if(mysql_num_rows($query) != 0)
{
//execute code
}

 

3. this line:

 

while($ROW = mysql_fetch_array($sql)){

 

will store both numerical and associative arrays in the variable $ROW, so to grab each individual field value you can either use the name of the field or the numeric order that the field is in the row. e.g

 

$id = $ROW['id'];
//or $id = $ROW[0];

 

4. this line:

 

$data .= t_MenuContent($ROW,$liclass);

 

makes no sense, unless t_MenuContent is a function with a return value. What is the logic for this line?

Link to comment
Share on other sites

2. this line:

 

if($numrows = mysql_num_rows($sql)){

 

does nothing, as it will always equate to TRUE. What you should do is check to make sure that at least one row has been grabbed from the query. e.g

 

Since mysql_num_rows() is being passed a string instead of a query result resource, it will throw a warning and the conditional will evaluate to FALSE. If it's changed to operate on the result resource, the conditional will work as intended, in spite of the fact that the assignment of mysql_num_rows() to a variable isn't necessary.

Link to comment
Share on other sites

hi thanks for replay

 

 

$numrows there cos I tried for loop for my problem but I deleted the loop after I could not figure out.

 

okay

 

I have a CSS design which is restourant menu. the menu itmes come from database.

 

there is a design issue that I need to have dynamic CSS CLASS name

 

<li class="classtop">Item1</li>
<li class="classbottom">Item2</li>
<li class="classtop">Item3</li>
<li class="classbottom">Item4</li>

 

in this example I pull items from database

 

so I have a line

 

which is this

 

<li class="????">$ROW['ItemName']</li>

 

here is class name hast to be "classtop" one time and has to be "classbottom"

 

it should be like this when it turns out to html

 

<li class="classtop">Item1</li>
<li class="classbottom">Item2</li>
<li class="classtop">Item3</li>
<li class="classbottom">Item4</li>

Link to comment
Share on other sites

2. this line:

 

if($numrows = mysql_num_rows($sql)){

 

does nothing, as it will always equate to TRUE. What you should do is check to make sure that at least one row has been grabbed from the query. e.g

 

Since mysql_num_rows() is being passed a string instead of a query result resource, it will throw a warning and the conditional will evaluate to FALSE. If it's changed to operate on the result resource, the conditional will work as intended, in spite of the fact that the assignment of mysql_num_rows() to a variable isn't necessary.

 

In the OP's code, $sql contains the result resource. This will also not account for a valid result resource with 0 rows grabbed. Unless I am missing something.

Link to comment
Share on other sites

i think this is what your trying to do ......

 

each menu item has a class asigned by its row "line striping" so each line is nto the same collor but it alternated between 2 classes

if im correct this is what you need...

 

$liclass = array('','ac_menu-item', 'menu-item-last');

$liclass[(((++$r)%2)+1)]

 

this will return position1 and position 2 in the array by each row looped i hope this helps...

Link to comment
Share on other sites

Alright, so a typical loop would look something like this:

 

 $sql = "SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'";
$query = mysql_query($sql) or die($sql . "<br />" . mysql_error());
if(mysql_num_rows($query) != 0)
{
    $index = 1;
    while($row = mysql_fetch_array($sql))
    {
        $item_name = $row['ItemName'];
        if($index % 1 == 0)
        {
            echo "<li class='classtop'>{$item_name}</li>";
        }
        if($index % 2 == 0)
        {
            echo "<li class='classbottom'>{$item_name}</li>";
        }
        $index++;
    }
}

Link to comment
Share on other sites

alot of code for only needing

 

echo "<li class='{$liclass[(((++$index)%2)+1)]}'>{$item_name}</li>";

but position 0 in the array has to be blank like in my example or this wont work...

 

true, it is a little more code, my style. The readability of your code is terrible. The classes most certainly do not need to be stored in an array, and more yet should not be included in the loop, being redefined each iteration. For 2 classes, hard coding them is fine. This is why I wrote the code the way I did.

Link to comment
Share on other sites

alot of code for only needing

 

echo "<li class='{$liclass[(((++$index)%2)+1)]}'>{$item_name}</li>";

but position 0 in the array has to be blank like in my example or this wont work...

 

this just worked perfect.

 

thanks so much.

 

I hope one day I can understand these loop stuff and match stuff very well in php. I was trying to figure out this from the morning.

 

also thanks for understanding my terrible English.

 

Thanks so much.

 

 

so the code is like this

 


<?php

function GetMenuContent($id){
    $sql = mysql_query("SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'");
        if(mysql_num_rows($sql)){
            while($ROW = mysql_fetch_array($sql)){
                $liclass = array('','ac_menu-item', 'menu-item-last');
                $data .= t_MenuContent($ROW,$liclass[(((++$r)%2)+1)]);
                
            }
        }else{
            $data =  "This section is empty!";
        }
        return $data;
    }

?>

Link to comment
Share on other sites

Alright, so a typical loop would look something like this:

 

 $sql = "SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'";
$query = mysql_query($sql) or die($sql . "<br />" . mysql_error());
if(mysql_num_rows($query) != 0)
{
    $index = 1;
    while($row = mysql_fetch_array($sql))
    {
        $item_name = $row['ItemName'];
        if($index % 1 == 0)
        {
            echo "<li class='classtop'>{$item_name}</li>";
        }
        if($index % 2 == 0)
        {
            echo "<li class='classbottom'>{$item_name}</li>";
        }
        $index++;
    }
}

 

this also very helpful but it won't work in my coding structure. it will but I need to change it.

 

<THEME Name={MenuWrap} VAR={ROW, CONTENT}>
<div id="menuwrap"> 
<div class="menu_section_ac" >
    <div class="menulevel1hover">
        <h2 class="menu"><div id="vegi"> <VAR>ROW['Title']</VAR> </div></h2>
    </div>
        <h3 class="menu"><VAR>ROW['Description']</VAR></h3>
</div>

<div class="menu_container">                     
    <div class="shadow-menu">
</div>
    <div class="menu-content">
        <ul>
            <VAR>CONTENT</VAR>
                                   
        </ul>
    </div><!-- #menu-content -->
  </div>    <!-- #menu-container -->
  
</div>    <!-- #menuwrap -->

</THEME>

<THEME Name={MenuContent} Var={ROW,LICLASS}>

    <li class="<VAR>LICLASS</VAR>">
        <h4 class="menu-content"><VAR>ROW['Title']</VAR></h4>
            <span class="menu-price"><VAR>ROW['Price']</VAR></span>
                <div style="clear:both; height:0px;"></div>
                    <div class="menu-item-desc">
                        <p><VAR>ROW['Detail']</VAR></p><br />
                </div>
    </li>

</THEME>

 

 

<?php

    $sql = mysql_query("SELECT * FROM category WHERE Active='2'");
    while($ROW = mysql_fetch_array($sql)){
        $_PAGE .= t_MenuWrap($ROW, GetMenuContent($ROW['CategoryID']));
    }

?>

 

<?php

function GetMenuContent($id){
    $sql = mysql_query("SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'");
        if(mysql_num_rows($sql)){
            while($ROW = mysql_fetch_array($sql)){
                $liclass = array('','ac_menu-item', 'menu-item-last');
                $data .= t_MenuContent($ROW,$liclass[(((++$r)%2)+1)]);
                
            }
        }else{
            $data =  "This section is empty!";
        }
        return $data;
    }

?>

Link to comment
Share on other sites

2. this line:

 

if($numrows = mysql_num_rows($sql)){

 

does nothing, as it will always equate to TRUE. What you should do is check to make sure that at least one row has been grabbed from the query. e.g

 

Since mysql_num_rows() is being passed a string instead of a query result resource, it will throw a warning and the conditional will evaluate to FALSE. If it's changed to operate on the result resource, the conditional will work as intended, in spite of the fact that the assignment of mysql_num_rows() to a variable isn't necessary.

 

In the OP's code, $sql contains the result resource. This will also not account for a valid result resource with 0 rows grabbed. Unless I am missing something.

 

Fair enough point about my first sentence; I didn't see the query execution wrapped in there. For the second part, if there are 0 rows returned the conditional will evaluate to false, which is what you'd want to happen if there are no records returned. There should be logic in place in the OP's code to prevent it from reaching that point if mysql_query() returns false, so aside from that there's nothing that would really prevent the conditional from working the way the OP intended. The t_MenuContent() user function may be another story.

 

But since all of that is irrelevant now that the OP has clarified it a bit:

$query = "SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'";
$result = mysql_query($query) or die( "<br>Query: $query<br>Produced error: " . mysql_error() );
if( mysql_num_rows($query) > 0 ) {
   $i = 0;
   while( $array = mysql_fetch_array($result) ) {
      $class = $i % 2 === 0 || $i === 0 ? 'classbottom' : 'classtop';
      echo "<li class=\"$class\">{$array['field_name']}</li>";
      $i++;
   }
}

 

Also, in your latest code, every iteration of the loop that contains an even value of $index will echo both sets of <li> tags because $index % 1 == 0 will evaluate to true for all positive integers and zero.

Link to comment
Share on other sites

Also, in your latest code, every iteration of the loop that contains an even value of $index will echo both sets of <li> tags because $index % 1 == 0 will evaluate to true for all positive integers.

 

fair point with that, overlooked it.

 

alot of code for only needing

 

echo "<li class='{$liclass[(((++$index)%2)+1)]}'>{$item_name}</li>";

but position 0 in the array has to be blank like in my example or this wont work...

 

this just worked perfect.

 

thanks so much.

 

I hope one day I can understand these loop stuff and match stuff very well in php. I was trying to figure out this from the morning.

 

also thanks for understanding my terrible English.

 

Thanks so much.

 

 

so the code is like this

 


<?php

function GetMenuContent($id){
    $sql = mysql_query("SELECT * FROM items WHERE Category = '".$id."' AND Active = '2'");
        if(mysql_num_rows($sql)){
            while($ROW = mysql_fetch_array($sql)){
                $liclass = array('','ac_menu-item', 'menu-item-last');
                $data .= t_MenuContent($ROW,$liclass[(((++$r)%2)+1)]);
                
            }
        }else{
            $data =  "This section is empty!";
        }
        return $data;
    }

?>

 

Again, this code will work, but it is not optimized. Hard coding an array inside of a loop is pointless and will decrease performance slightly. I understand that is how t_menuContent is setup. But at least place the array outside of the loop. For the love of God. Also, please use the debugging steps that me and pika have provided, proper debugging is crucial and can save your hours of searching for errors in your code.

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.