0

I have the following code, to split the resulting array up by the Category field.

    $query =    "SELECT * FROM livestock    
                WHERE   Category = 'monitor' 
                    OR  Category ='bearded' 
                    OR  Category ='chameleon' 
                    OR  Category ='skink' 
                    OR  Category ='small' 
                    OR  Category ='medium' 
                    OR  Category ='terrestrial'
                    OR  Category ='arboreal'
                    OR  Category ='leopard'";

    $result = mysqli_query($con, $query) or die(mysqli_error($con));        

    $rows = array();

    while ( $row = mysqli_fetch_array($result)){            
            $rows[$row['Category']][] = $row;}

I then echo this out to the page in several places using the following code:

    foreach($rows['MONITOR'] as $row)
    {
        $commondraft = $row['Name'];
        $current = $row['Category'];

        if($current==$previous){
echo"<a href='/stocklist/".$row['id']."/".commonName($commondraft)."' class='row'>";        
        echo"<div class='common'>".$row['Name']."</div>"; 
        echo"<div class='descr'>".$row['Description']."</div>";
        echo"<div class='sex'>".$row['Sex']."</div>"; 
        echo"<div class='age'>".$row['Age']."</div>"; 
        echo"<div class='size'>".$row['Size']."</div>";  
        echo"<div class='origin'>".$row['Origin']."</div>"; 
        echo"<div class='scientific'>".$row['Scientific']."</div>"; 
        echo"<div class='prices'>".$row['Price']."</div>"; 

        echo"</a>";
        }
        $previous = $current;
        }
    echo"</div>";

But each time i echo this out using the foreach() loop it misses the first record.

How can i work a way around this and what's causing it?

Thanks in advance

2
  • 3
    Isn't this because of if($current==$previous)? What is $previous set to at the start of the loop? Commented Mar 7, 2015 at 22:55
  • @Cyclone - you were right! The whole $current / $previous if() statement isnt required anymore since i split the array. it was from an old version of the code where i was splitting it by looking for the point at which the Category changed. So thanks! :D Commented Mar 7, 2015 at 23:01

1 Answer 1

2

My guess would be that this is caused by the following line in the loop:

if($current==$previous){

Since you only output a link if $current is equal to $previous, so the question is if you really initialize $previous correctly before your foreach loop. You will need to initialize $previous before the loop using something like this:

$previous = $rows['MONITOR'][0]['Category'];
Sign up to request clarification or add additional context in comments.

Comments

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.