简体   繁体   中英

PHP MYSQLI while loop gets only 1 row


I have two ID in the 'appointment' table which are 1 and 2(ID). The two ID from the appointment table are came from the 'time' table. The time table have this ID (1,2,3,4,5).


in this query, the while loop echo the two ID which are 1 and 2(ID) which is correct.

<?php
            //appointment table
            $query1 = "SELECT * FROM appointment WHERE date_app = '$date' AND status = 'Active'";
            $result1 = mysqli_query($conn,$query1) or die("Error: ".mysqli_error($conn));;  


            while($row1=mysqli_fetch_array($result1)){
                $t = $row1['time_id'];
        ?>  
            <tr><td>
            <a href=""><?php echo $t; ?></a>
            </td></tr>

            <?php } ?>

in this query, i need to get all the ID that are not equal to value of the above query. when i echo ,I am getting a result of 2,3,4,5(ID) which is supposed to be 3,4,5(ID) only.

<?php
           //time table
            $query11 = "SELECT * FROM time WHERE time_id != '$t' ORDER BY STR_TO_DATE(time_sched,'%h:%i%p')";
            $result11 = mysqli_query($conn,$query11) or die("Error: ".mysqli_error($conn));;    

            while($row11=mysqli_fetch_array($result11)){

        ?>  
            <tr><td>
            <a href=""><?php echo $row11['time_id']; ?></a>
            </td></tr>

            <?php } ?>

What is wrong with my code in the appointment table?

Classic

 $ids = [];
 while($row1=mysqli_fetch_array($result1)){
    $ids[] = $row1['time_id'];

 //..... other code
 }//end of while loop for clarity.

 $query11 = "SELECT * FROM time WHERE time_id NOT IN(".implode(',', $ids).") ORDER BY STR_TO_DATE(time_sched,'%h:%i%p')";

You are only using the last ID from the first loop. So you need to store those IDs in an array and then using them in the input for IN.

In other words the variable $t is overwritten on each iteration of the first loop. Then you use it in your second query, so it only retains the last value from the previous loop.

Make sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM