简体   繁体   中英

how to check if the record exist using while loop in php with submit for in while loop

I am having a trouble checking if the data exist in the database. Actually I've got the logic how to check it. But I am having a trouble when I am submitting the form it show the message for all the records for example:


| 1 | book1 | 34234324
| 2 | book2 | 839423423
| 3 | book3 | 323423423

So i have a submit inform inside the loop. I want to specifically want to display the error message on the specific record that I am checking..

Here is my code

<?php
date_default_timezone_set('Asia/Manila');
$db_server = "localhost"; // server 127.0.0.1
$db_user = "root"; // databe user name
$db_pass = ""; //password
$db_name = "ue_library"; //database name 

$dbcon = new mysqli($db_server,$db_user,$db_pass,$db_name);
if ($dbcon->connect_error) 
{
die("Connection failed: " . $dbcon->connect_error);
}
?>

<?php 
$d = $dbcon->query("SELECT * FROM book_reservation") or die(mysqli_error());
?>
<?php 
if(!empty($d))
{
    foreach ($d as $key => $value) 
    {

  ?>
   <div style="">
   <?php echo $value['barcode_num'];?><span style="padding-left:100px;">
<?php      echo $value['book_title'];?>
<form method="post" action="">
     <input type="text" name="barcode_num" class="search_code">
     <input type="hidden" name="reserveID" 
     value="<?php echo     $value['reserveID'];?>">
     <input type="submit" name="check"  value="Check Availability">
  </form>
  <?php
    if(isset($_POST['check']))
    {
        $barcode_num= trim($_POST['barcode_num']);
        $reserveID = trim($_POST['reserveID']);

        $f = $dbcon->query("SELECT * FROM book_reservation 
   WHERE barcode_num = '$barcode_num' AND reserveID='$reserveID'") 
   or    die(mysqli_error());
        $row = $f->fetch_assoc();

        if($row['barcode_num'] == $barcode_num &&
       $row['reserveID'] == $reserveID)
        {
            echo 'Meron';
        }
        else
        {
            echo 'wala';
        }


    ?>

    <?php
    }
    ?>
</span>
<?php
    }
}
?>

$connection=mysqli_connect($host,$user,$pass,$database);
do {
    $random=mt_rand(1000,9999);
    $result=$connection->query("SELECT * FROM table WHERE email = '.$random.'");
    $num_rows = $result->num_rows;
}
while ($num_rows > 0);

You aren't iterating through your initial record set correctly. For example after:

$d = $dbcon->query("SELECT * FROM book_reservation") or die(mysqli_error());

You need to use a 'while' loop instead and loop through like:

$d = $dbcon->query("SELECT * FROM book_reservation") or die(mysqli_error());
while($row = $d->fetch_assoc) {
}

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