Home > Blockchain >  I have a problem printing within a foreach loop
I have a problem printing within a foreach loop

Time:12-20

this is my table on database

<?php
require '../koneksi.php';

$kategori=mysqli_query($conn, "SELECT * FROM kategori");

?>
<li >
            <div >
            <label for="kategori" >Kategori surat</label>
            <select  name="kategori" id="kategori" required>
                <option value="" selected="">Pilih kategori surat</option>
                <?php
                    foreach ($kategori as $key => $value) {                 
                ?>
                <option value="<?php echo $value['id']; ?>"><?php echo $value['kategori']; ?></option>
                <?php
                    }
                ?>
            </select>
            <script type="text/javascript" src="../JQuerydashboard.js"></script>
            </div> <!-- akhir dari kategori -->
        </li>

i have database with table name is "kategori". "kategori" have id from 1-5. i want to print that id from 1-3. how to do it?

CodePudding user response:

<li >
            <div >
            <label for="kategori" >Kategori surat</label>
            <select  name="kategori" id="kategori" required>
                <option value="" selected="">Pilih kategori surat</option>
                <?php
                    $counter = 0; 
                    foreach ($kategori as $key => $value) { 
                    if($counter > 3){
                       break;
                    }
                ?>
                <option value="<?php echo $value['id']; ?>"><?php echo $value['kategori']; ?></option>
                <?php
                    $counter  ;
                    }
                ?>
            </select>
            <script type="text/javascript" src="../JQuerydashboard.js"></script>
            </div> <!-- akhir dari kategori -->
        </li>

Just have to create a counter, and everytime the counter increments it will represent an id and if it is bigger than 3 you just end the foreach loop.

  • Related