php – "while($row = mysqli_fetch_array($result))" might be empty?-ThrowExceptions

Exception or error:

Im really confused now please help
… This is the edit/update part which you will edit chosen user. The problem is i think $row or array is empty. The problem is that part. Im accepting any advice to my code to make it better.


Output

This is the output when i click edit button


update.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<form method="POST" action="uprec.php">
<?php  

if(isset($_POST["borrower_id"])){
    
    $output = '';
    $connect = mysqli_connect("localhost", "root", "", "librarydb");
    $query = "SELECT * FROM tbl_books WHERE id = '".$_POST["borrower_id"]."'";
    $result = mysqli_query($connect, $query);
    echo "Connected ";
 
    while($row = mysqli_fetch_array($result)){
        echo "fetch success";

    }
    echo "fetch failed";
  
}

else{
    echo "Not Connected";
}

?>
    <input type="submit" name="update" id="update" value="UPDATE" class="btn btn-success" />
</form>
</body>
</html>

database.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>

<head>
  <title>Database</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <script src="script/livesearch.js"></script>
</head>

<body>
  <nav class="navbar navbar-expand-md bg-dark navbar-dark">
    <a class="navbar-brand" href="#">Home</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    	<span class="navbar-toggler-icon"></span>
  	</button>
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="#">Books</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Transactions</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Accounts</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="logout.php">Logout</a>
        </li>
      </ul>
    </div>
  </nav>


  <?php
	if(!empty($_SESSION)) {
?>
    <div class="container p-3">
      <h1 class="">Library Database</h1>
      <hr><br>
      <form>
        <div class="input-group ">
          <div class="input-group-prepend">
            <span class="input-group-text">Search</span>
          </div>
          <input type="text" name="search_text" id="search_text" class="form-control" />
        </div>
      </form>
      <br />
      <button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#addbook_modal">Add Book</button>
      <div id="result"></div>
    </div>
    <hr>
    <?php
	}else echo '<div class="alert alert-danger alert-dismissible fade show">
    <strong>Login Required!</strong> You needed to be login first before you can access the database.
    <a href="login.php"> Go back to login</a>
    </div>';
?>
</body>

</html>
<script>
  $(document).ready(function() {
    $('#addbook_form').on("submit", function(event) {
      event.preventDefault();
      if ($('#booktitle').val() == "") {
        alert("Book Title is required");
      } else if ($('#category').val() == '') {
        alert("Category is required");
      } else if ($('#author').val() == '') {
        alert("Author is required");
      } else if ($('#publishername').val() == '') {
        alert("Publisher Name is required");
      } else if ($('#datepublished').val() == '') {
        alert("Date Published is required");
      } else if ($('#copies').val() == '') {
        alert("Copies is required");
      } else {
        $.ajax({
          url: "insert.php",
          method: "POST",
          data: $('#addbook_form').serialize(),
          beforeSend: function() {
            $('#addbtn').val("Inserting");
          },
          success: function(data) {
            $('#addbook_form')[0].reset();
            $('#addbook_modal').modal('hide');
            $('#result').html(data);
          }
        });
      }
    });
  });

  $(document).on('click', '#editbtn', function() {
    var borrower_id = $(this).attr("id");
    $.ajax({
      url: "update.php",
      method: "POST",
      data: {
        borrower_id: borrower_id
      },
      success: function(data) {
        $('#borrower_detail').html(data);
        $('#editbook_modal').modal('show');
        console.log(data);
      }
    });
  });
</script>

<div id="addbook_modal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Add Book</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <form method="POST" id="addbook_form">
          <div class="form-group">
            <label>Book Title:</label>
            <input type="text" name="booktitle" id="booktitle" class="form-control" placeholder="Title of the Book">
          </div>
          <div class="form-group">
            <label>Category:</label>
            <select name="category" id="category" class="custom-select">
              <option>Art</option>
              <option>English</option>
              <option>Math</option>
              <option>Science</option>
              <option>Filipino</option>
            </select>
          </div>
          <div class="form-group">
            <label>Author:</label>
            <input type="text" name="author" id="author" class="form-control" placeholder="Author of the Book">
          </div>
          <div class="form-group">
            <label>Publisher Name:</label>
            <input type="text" name="publishername" id="publishername" class="form-control" placeholder="Name of the Publisher">
          </div>
          <div class="form-group">
            <label>Date Published</label>
            <input type="date" name="datepublished" id="datepublished" class="form-control" placeholder="Date of Publication">
          </div>
          <div class="form-group">
            <label>Copies</label>
            <input type="number" name="copies" id="copies" class="form-control" placeholder="Number of Copies">
          </div>
          <div class="form-group">
            <button id="addbtn" class="btn btn-success">Add</button>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div id="editbook_modal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Edit Book Details</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body" id="borrower_detail">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

fetch.php

<?php
session_start();
include ('connection.php');
	if(!empty($_SESSION)) {
		$output = '';
		if(isset($_POST["query"]))
		{
		 	$search = mysqli_real_escape_string($connect, $_POST["query"]);
		 	$query = "
		  		SELECT * FROM tbl_books
		  		WHERE booktitle LIKE '%".$search."%'
		  		OR category LIKE '%".$search."%' 
		  		OR author LIKE '%".$search."%' 
		  		OR copies LIKE '%".$search."%' 
		  		OR publishername LIKE '%".$search."%'
		  		OR datepublished LIKE '%".$search."%'
		 	";
		}
		else
		{
		 	$query = "
		  		SELECT * FROM tbl_books ORDER BY id DESC
		 	";
		}
		$result = mysqli_query($connect, $query);
		if(mysqli_num_rows($result) > 0)
		{

		 	$output .= '
		  		<div class="table-responsive" id="employee_table">
		   			<table class="table table-bordered">
		   				<thead>
			    			<tr>
			     				<th>Book Title</th>
			     				<th>Category</th>
			     				<th>Author</th>
			     				<th>Publisher Name</th>
			     				<th>Date Published</th>
			     				<th>Copies</th>
			     				<th>Action</th>
			    			</tr>
		    			</thead>
		 	';	
		 	while($row = mysqli_fetch_array($result))
		 	{

		  		$output .= '
		   			<tr>

		    			<td>'.$row["booktitle"].'</td>
					    <td>'.$row["category"].'</td>
					    <td>'.$row["author"].'</td>
					    <td>'.$row["publishername"].'</td>
					    <td>'.$row["datepublished"].'</td>
					    <td>'.$row["copies"].'</td>
					    <td><button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
					    	<button type="submit" class="btn btn-danger btn-sm">Delete</button>
					    </td>
		   			</tr>
		  		';
		 	}
		 	echo $output;
			}
		else
		{
		 	echo 'Data Not Found';
		}
	
	}else echo '<div class="alert alert-danger alert-dismissible fade show">
        <strong>Login Required!</strong> You needed to be login first before you can access the database.
        <a href="login.php"> Go back to login</a>
        </div>';
?>
How to solve:

Currently
$_POST[“borrower_id”]
is always “editbtn” all the time. So query always returns zero entries.

Your problem is this

<button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>

and this should probably something like this

<button type="submit" class="btn btn-success btn-sm" id="editbtn" bookid='.$row['id'].'>Edit</button>

$row[‘id’] depends on whatever your id field is named.

Also you have to change

var borrower_id = $(this).attr("id");

to

var borrower_id = $(this).attr("bookid");

This should work.

Leave a Reply

Your email address will not be published. Required fields are marked *