Home > Back-end >  How to check whether a text variable is equal to an Array
How to check whether a text variable is equal to an Array

Time:05-30

My requirement is to check whether a text variable is equal or not to an mysql output array.

The mysql output array I have taken as follows,

$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
    $avail_books[] = $row['book_name']; // Inside while loop
}

Now I need to check whether user have entered any book from which included in above array.So I have implemented as below.

$(document).ready(function(){
  $('#insert_form').on("submit", function(event){  
    event.preventDefault();
    $('#book_name').val()=$book_required;


    if(in_array($book_required,$avail_books))
    {
      alert("Not Available");
    }
    else{
      $.ajax({

        url:"books.php",  
        method:"POST",  
        data:$('#insert_form').serialize(),  
        beforeSend:function(){  
          $('#insert').val("Inserting");  
        },  
        success:function(data){  
          $('#insert_form')[0].reset();  
          $('#add_data_Modal').modal('hide');  
          $('#employee_table').html(data);  
        }  

      });  
    }
  }
}

But this is not working. Can someone show where I have messed this?

CodePudding user response:

There can be other ways to accomplish what you want.

For example, use the following query:

SELECT count(*) FROM takenbooks where book_name = ? 

But for How to check whether a text variable is equal to an Array and based on your original code, the normal way will be to pass the user input data (I believer is $('#book_name').val()) thru ajax to a PHP file to check whether this data is in the array , then return the result back (or do further processing)

For the HTML

<script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>


<form id=insert_form>
<input type=text id="book_name">
<input type=submit>
</form>

<script>
$(document).ready(function(){
  $('#insert_form').on("submit", function(event){  
   event.preventDefault();

  $.ajax({
   type: "POST",
   url: 'checkdata.php',
   data: {data1: $('#book_name').val()},
   success: function(data){
   alert(data);
   },
    error: function(xhr, status, error){
    console.error(xhr);
   }
  });
 })
})
 </script>

For the PHP (checkdata.php)

<?php
 
if (isset($_POST["data1"])){

$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);

while( $row = mysqli_fetch_assoc( $result)){
    $avail_books[] = $row['book_name']; // Inside while loop
}

   if(in_array($_POST["data1"],$avail_books)) {
     echo "Not Available";
     } else {

    // Place insert query here

     echo "New Record inserted";

    }
}

?>

CodePudding user response:

It might have some Syntax error but thats the basic concept of what you are trying to achieve. Someones enters text, script searches the database and returns the results.

<html>
<body>
<form action="" method="POST">
 <input type="text" name"book" required placeholder="Type the name of the Book" />
 <input type="submit" value="Search Book" />
</form>

<div><h2>Results:</h2>

<?php

if(isset($_POST['book'] && !empty($_POST['book'])){

   mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

   $connect = new mysqli("localhost", "root", "", "newbooks");
   $stmt = $mysqli->prepare("SELECT ID, book_name FROM takenbooks WHERE book_name LIKE ? ORDER BY ID DESC;");
   $stmt->bind_param("s", "%"   $_POST['book']   "%");
   $stmt->execute();
   $result = $stmt->get_result();
  
   while ($row = $result->fetch_assoc()) {
      echo '<p>Book \"' . $row['book_name'] . '\" was found.<br/></p>';
   }
}

?>
</div>
</body>
</html>

CodePudding user response:

You can first get the list of books once, then write a Javascript array from which to search for the entered book name. (This may not be practical if the list of books changes quite often, or the list is extremely long.)

<?php

$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
$avail_books = [];
while( $row = mysqli_fetch_assoc( $result)){
    $avail_books[] = $row['book_name']; // Inside while loop
}

?>
<!DOCTYPE html>
<html>
<body>
<form id="insert_form">
  Book name: <input type="text" name="book_name">
  <input type="submit" value="Check for availability">
</form>
<div id="available"></div>
<script>

const avail_books = <?php json_encode($avail_books); ?>;

document.querySelector('#insert_form').addEventListener(function (evt) {
  evt.preventDefault();

  let book_name = evt.target.book_name.value;
  let not_available = (-1 === avail_books.indexOf(book_name))? 'not': '';
  document.querySelector('#available').innerHTML = book_name   " is "   not_available   " available.";
});
</script>    

</body>
</html> 

PHP, on the server, gets the books and stores the list in a PHP array. And when writing out HTML and Javascript use PHP to write out a Javascript avail_books array containing the book names retrieved from the database.

Now the server can send the client the HTML/Javascript code for rendering. Once loaded in the browser, and if you "View Source", the Javascript code will look something like this:

const avail_books = ["To Kill a Mockingbird", "Animal Farm", "Atlas Shrugged"];

With that the user can check the list of books without having to send a query to the server with every inquiry. It's faster and uses less resources.


enter image description here


  • Related