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?
3
Answers
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.
There can be other ways to accomplish what you want.
For example, use the following query:
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 believe 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
For the PHP (checkdata.php)
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, 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:
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.