Brad Guy
Brad Guy

Reputation: 91

How to get the row number for each item returned

I am trying to use the XSwitch jquery script and dynamically create the "section id" automatically but am stuck.

How do I give each section an "id" starting at 0? Some items have 2 or 3 images, some have 30+.

$result = mysqli_query($conn,"SELECT * FROM Images WHERE stock=".$_GET['stock']." ORDER BY orderIndex");
while($row = mysqli_fetch_array($result)){
  $count = $result->num_rows;
  if ($count) {
    $photos .= '<div class="section" id="section__NEED___NUMBER" style="background-image: url(inventory/'.$category.'/large/'.$stock.'_'.$row['id'].'.jpg)"></div>';
  } else {
    $photos = 'No Photos are currently available';
  }
}

Upvotes: 1

Views: 25

Answers (1)

Sean
Sean

Reputation: 12433

You can use a simple counter variable ($counter = 0;), which you increase on each loop ($counter++;`) -

$counter = 0;
$result = mysqli_query($conn,"SELECT * FROM Images WHERE stock=".$_GET['stock']." ORDER BY orderIndex");
$count = $result->num_rows;
if ($count) {
    $photos = "";
    while($row = mysqli_fetch_array($result)){
        $photos .= '<div class="section" id="section__'.$counter.'" style="background-image: url(inventory/'.$category.'/large/'.$stock.'_'.$row['id'].'.jpg)"></div>';
        $counter++;
    }
} else {
    $photos = 'No Photos are currently available';
}

note, you had your $count = $result->num_rows;if ($count) {...} inside your while() loop, when it should be outside.

Upvotes: 2

Related Questions