1

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';
  }
}
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
Brad Guy
  • 93
  • 1
  • 11

1 Answers1

2

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.

Sean
  • 12,443
  • 3
  • 29
  • 47
  • Works perfectly. Thanks! – Brad Guy Jan 15 '17 at 04:49
  • as you have `$_GET['stock']` unfiltered in your query, please read [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Sean Jan 15 '17 at 04:51