Ajax mysql examples


It is possible to use AJAX to pull data from a MySQL database. The HTML file that was created in the earlier part of this tutorial can be used to demonstrate this with a few updates and with the creation of the new database.

First some MySQL queries must be created.  Either a new database can be created or an existing table can be used.  For the sake of this example, let’s say that ajax_sample.sql was imported to a database and it creates the table ajax-sample and inserts all of the necessary data rows.  This table has the following columns:

  • aj_name – name of person
  • aj_age – age of person
  • aj_sex – gender of person

In order to build queries from the HTML file, more elements need to be added. The additional inputs that are necessary are the following:

1. Maximum Age – This is a text input that allows the maximum age to be returned to be set.

2. Gender– This is a selection input that allows the user  to select the person’s gender.


The following example shows this added to the HTML and JavaScript:

Example: <html>



<script language=”javascript” type=”text/javascript”>


//Support Code for Browser

function ajaxFunction(){

var ajaxRequest;  // This is necessary for AJAX



// Firefox, Opera, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer


ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”);

} catch (e) {


ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (e){

// Something is incorrect

alert(“Current browser does not work.”);

return false;




// Function to receive data from server

ajaxRequest.onreadystatechange = somefunction(){

if(ajaxRequest.readyState == 4){

document.someForm.date.value = ajaxRequest.responseText;



var age = document.getElementById(‘age’).value;

var sex = document.getElementById(‘sex’).value;

var queryString = “?age=” + age + “&sex=” + sex;

ajaxRequest.open(“GET”, “ajax-example.php” + queryString, true);







<form name=’someForm’>

Max Age: <input type=’text’ id=’age’ /> <br />

Sex: <select id=’sex’>




<input type=’button’ onclick=’ajaxFunction()’ value=’Query MySQL’ />





In this new piece of JavaScript, a query string has been built (var queryString = “?age=” + age +  “&sex=” + sex;) to pass the information from the HTML form to the PHP script.  The query string allows information to be passed by appending data onto the URL. In the query string, notice that each variable is separated by and ampersand (&).

The next step is to build a PHP script that will use these variables to run a MySQL query. To prevent harmful user input, a special function called mysql_real_escape_string will be used.  The following example contains the code for the new ajax-sample.php file.

Example: <?php

$dbhost = “localhost”;

$dbuser = “dbusername”;

$dbpass = “dbpassword”;

$dbname = “dbname”;

//Connect to server

mysql_connect($dbhost, $dbuser, $dbpass);

//Choose database

mysql_select_db($dbname) or die(mysql_error());

// Get data from query string

$age = $_GET[‘age’];

$sex = $_GET[‘sex’];

// Escape User Input to help prevent SQL Injection

$age = mysql_real_escape_string($age);

$sex = mysql_real_escape_string($sex);

//Build query

$query = “SELECT * FROM ajax_example WHERE ae_sex = ‘$sex'”;


$query .= ” AND ae_age <= $age”;

//Execute query

$qry_result = mysql_query($query) or die(mysql_error());


//Build Result String

$display_string = “<table>”;

$display_string .= “<tr>”;

$display_string .= “<th>Name</th>”;

$display_string .= “<th>Age</th>”;

$display_string .= “<th>Sex</th>”;

$display_string .= “</tr>”;


// Insert row in table for each person returned

while($row = mysql_fetch_array($qry_result)){

$display_string .= “<tr>”;

$display_string .= “<td>$row[ae_name]</td>”;

$display_string .= “<td>$row[ae_age]</td>”;

$display_string .= “<td>$row[ae_sex]</td>”;

$display_string .= “</tr>”;



echo “Query: ” . $query . “<br />”;

$display_string .= “</table>”;

echo $display_string;



This completes the initial HTML and PHP file setup.  For the next step the HTML page must update correctly when the query is returned.  This means that a segment of the HTML file will be updated with the MySQL result display_string.

This entry was posted in Ajax Tutorials and tagged , , , , , , , . Bookmark the permalink.

3 Responses to Ajax mysql examples

  1. I needed to create you the little bit of observation in order to thank you as before for these magnificent principles you have discussed above. This has been certainly pretty open-handed with people like you to allow freely precisely what many of us would’ve offered for sale as an ebook in order to make some profit on their own, certainly seeing that you might well have tried it if you wanted. Those principles likewise acted to be a great way to fully grasp most people have a similar fervor like my very own to know somewhat more in terms of this problem. I am sure there are a lot more enjoyable times up front for individuals who read carefully your blog.

  2. I happen to be writing to make you know of the terrific discovery our princess experienced going through your web page. She picked up many things, not to mention what it’s like to possess an awesome giving character to make the mediocre ones very easily fully grasp a number of hard to do matters. You really did more than our expected results. Thank you for producing those precious, healthy, edifying and as well as fun tips about this topic to Jane.

  3. Oh my goodness! a great write-up dude. Many thanks Nevertheless I am experiencing problem with ur rss . Do not know why Unable to sign up for it. Can there be anyone finding identical rss issue? Anyone who knows kindly respond. Thnkx

Leave a Reply

Your email address will not be published.