Skip to content Skip to sidebar Skip to footer

Dynamically Query A Database To Check For Value

I need to check if a certain value 'SheetNumber' is in my mysql database dynamically. I have seen it done on popular web sites and I am trying to find a good tutorial to outline it

Solution 1:

You will need to do this using Ajax. I recommend the Jquery library. Install it using the Jquery documentation, and then use something like the following:

Javascript:

functionmakeAjaxRequest()
{
   var url="script-that-checks-db.php";
   $.get(url,{},verifyDb);
}

functionverifyDb(response)
{
    if (response==1)
    {
       //The value exists, do what you want to do here
    }

    else
    {
      //The value doesn't exist
    }
}

You can have makeAjaxRequest() invoked when someone clicks a link, clicks a button, or anything else, e.g:

<ahref="#"onclick="makeAjaxRequest();">Check database</a>

The php code of the file script-that-checks-db.php (of course, name it something different) will be responsible for checking the db. The code would look something like this.

PHP:

<?php//Do the mysql query and find out if the value exists or not.if ($exists==true)
   echo"1"; //1 will indicate to javascript that the value exists.elseecho"0";
?>

You could also use JSON here rather than the 0/1 method, but because you are new I think this will be simple enough for you.

Hope this helps, if you have any questions feel free to ask. Also, feel free to change the function and file names.

Solution 2:

It's pretty simple; check the jQuery docs on the AJAX functions: jQuery.get()

You'll need to set up a simple PHP service that returns raw data, XML, or JSON-formatted data that you can then interpret with your jQuery callback function.

Example:

functioncheckData(userInputValue) {
  jQuery.get('ajax-backend.php?value='+userInputValue, false, function(data) { alert('Response from server: ' + data)});
}

Instead of using alert() to display the response from the server, you'd probably want to interpret this value and change something on the page indicating whether the operation was successful.

Here's a more detailed example from a previous question: Beginning jQuery help

Solution 3:

I assume that by "dynamically" you mean "without leaving the page", suggesting a "AJAX" solution.

You cannot the access your database using client-side JavaScript, I recommend using a JavaScript library/framework like JQuery to call a PHP script "behind the scenes" that does what you want.

Post a Comment for "Dynamically Query A Database To Check For Value"