Home > database >  How to count the arrays from a result of a query?
How to count the arrays from a result of a query?

Time:09-30

I have a query that I make using PHP and it returns me all the rows that satisfied the condition that was given, now, I'm wondering if there's a way to count each number of row a result of a query has and pass that number to an id of an element on HTML?

<?php
     $res2 = mysqli_query($con,"SELECT NAME, PRICE FROM product WHERE AVAILABLE = 1 AND ID_CATEGORY = 17");
?>
<body>
      <?php
         while($row = mysqli_fetch_row($res2)) {
            print_r($row);
            ?>
               <div class="item">
                  <img class="trj_img_cls" src="RSC/COMING_SOON.jpg" alt="" id="imgDG<?php  ?>">
                  <div class="texto_trj">
                     <div class="nombre_producto">
                        <h2 id="ttlDG<?php  ?>">título</h2>
                     </div>
                     <div class="precio_producto">
                        <i class="icon-dollar"></i>
                        <label id="prDG<?php  ?>">0.00</label>
                     </div>
                     <div class="caracteristicas">
                        <ul id="caractDG<?php  ?>"></ul>
                     </div>
                  </div>
               </div>
            <?php
         }
      ?>
</body>

I put <?php ?> because there I want to add the variable (number of the row) so it complements the actual id and then i'm able to look for that id with javascript. Another thing is that I use the print_r() just to see if the elements were appearing.

CodePudding user response:

This can be done by setting an $increment variable to 1 at the start of the while loop, and incrementing it at the end of the loop.

<?php
    $increment = 1;
    while($row = mysqli_fetch_row($res2)) {

And then using it like this:

id="imgDG<?php echo $increment; ?>">

And then incrementing it at the end:

        <?php
     $increment  ;
     }
  ?>
  • Related