Putting MySQL under your PHP/AJAX hood really gives your apps horsepower.
If you've read my last two tips, you should by now have installed an Apache Server running PHP and a MySQL Database Server locally on your PC. Even if you haven't, you can benefit from this tip because if you have the installment on a "remote" Web server, the scripts provided here will still work. But you might have to do a little tweaking.
I also expect you to have installed a version of SQLyog because it will be used as database tool in this tip.
For your convenience, here are my previous two tips.
Importing Data Using SQLyog
As you might know, I am a big fan of Elvis Costello. Therefore, the data that we will use in this tip is a table called ec_albums, which contains all the albums I have on CD by Mr. Costello. To save you a lot of work, I have created a small SQL file that you can import using SQLyog.
So let's stop "Talking in the Dark" and move on to the fun stuff.
First, download the SQL dump. Save the file and unzip it somewhere on your computer.
Then, open SQLyog, find the mydb database you created in my previous tip, right-click on mydb, and select Restore from SQL Dump, as shown in Figure 1.
Figure 1: Restore from SQL dump. (Click images to enlarge.)
On the Execute Query(s) From A File dialog, navigate to where you saved the downloaded SQL file and press Execute.
Figure 2: Import the downloaded SQL file.
If you receive a few warnings, just press OK. When you see the picture in Figure 3, the import is done. Press Done.
Figure 3: Your file has been imported.
When you return to the SQLyog workbench, press F5 to refresh and confirm that you now have a table called ec_albums. Click on the Table Data tab to view the contents of the table.
Figure 4: Now you can see your data.
Success! That data is now imported and ready to use.
"(What's So Funny 'Bout) PHP, Love and Understanding"
Before we start writing the PHP scripts, let me give you an overview of what we will be doing during this tip. This tip is built around the PHP and AJAX tip Jeff Olen recently wrote. I have changed most of the code to suit my needs, but if you read Jeff's tip, you'll know pretty much what the idea is and how Jeff's code works.
So let's move on to the fun part and start defining the first PHP script, which will be a script to hold the database logon information. (At the end of this tip, you can download a zip file that contains all the PHP scripts for this tip.)
The first script, connect.php, looks like this:
connect.php
<?php
//======================================================================// Connect to server/database
//======================================================================$dbHost = "localhost";
$dbUser = "root";
$dbPass = "1234";
$dbDatabase = "mydb";
?>
The next script, called ec.php, is the script that contains the form where you can search for the album titles.
ec.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Search Costello Albums</title>
</head>
<script src="/select.js"></script>
<script>
<!--
// Send the request to the server
function sendRequest()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
// Get input data
var data = parent.document.getElementById("search").value;
// Get length of string
//if ( data.length < 3 ) return;
// set up the url for the server request
var url="ec-load.php";
url=url+"?data="+data;
// random number to avoid caching
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
//-->
</script>
<body>
<form>
<b>Search for Elvis Costello albums</b>
<p>
<table border="1" cellspacing="0" cellpadding="3">
<tr>
<td>
Enter title or part of it (*=view all)
</td>
<td>
<input size="30" maxlength="50">
<!--<input size="30" maxlength="50">-->
</td>
</tr>
<tr>
<td colspan="2">
<input value="Search">
</td>
</tr>
</table>
</form>
<!-- Display data result -->
<div></div>
</body>
</html>
I will not discuss every statement in the script, but please notice that I have moved the sendRequest JavaScript function out of the select.js document because I then can use it in more general terms.
Other than that, the ec.php script is pretty straightforward and should not be too hard to understand.
The next script, called ec-load.php, is the script used to read the HTML input form, connect to the MySQL database, read the data from the ec_albums form, and return the result back to the ec.php script through the AJAX "tunnel."
ec-load.php
<?php
//=============================================================================
// Read input
//=============================================================================
$data = $_REQUEST['data'];
if ($data == "") {
echo "<b>Please enter a search string</b>";
exit;
}
// Save for display on entries found
$saveData = $data;
//=============================================================================
// Connect to server/database
//=============================================================================
include "connect.php";
//=============================================================================
// Select data from table according to search string
//=============================================================================
$conn = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
if ( $data == '*' )
{
$data = "";
$limit = 200;
} else {
$limit = 10;
}
// Check input
$data = check_input($data);
mysql_select_db("$dbDatabase", $conn) or die ("Couldn't select the database.");
$sql = "SELECT * FROM ec_albums WHERE title LIKE " . $data . " ORDER BY relyear, title LIMIT " . $limit;
$result=mysql_query($sql, $conn);
$num_rows = mysql_num_rows($result);
echo "<table border=""1"" cellspacing=""0"" cellpadding=""3"">";
echo "<tr>";
echo "<td colspan=""3"" bgcolor=""#e8e8e8"">";
echo "Entries found: $num_rows, when searching on: <b><i>$saveData</i></b><br>";
echo "</td>";
echo "</tr>";
echo "<tr bgcolor=""#c0c0c0"">";
echo "<td>";
echo "Title<br>";
echo "</td>";
echo "<td align=""center"">";
echo "Release year<br>";
echo "</td>";
echo "<td>";
echo "Producer<br>";
echo "</td>";
while($row = mysql_fetch_array($result))
{
$title = $row['title'];
$producer = $row['producer'];
$relyear = $row['relyear'];
echo "<tr>";
echo "<td>";
echo "$title<br>";
echo "</td>";
echo "<td>";
echo "$relyear<br>";
echo "</td>";
echo "<td>";
echo "$producer<br>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
//=============================================================================
// Check input to avoid SQL injection
//=============================================================================
function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (!is_numeric($value))
{
$value = "'%" . mysql_real_escape_string($value) . "%'";
}
return $value;
}
?>
One thing to pay attention to is the check_input function, which prevents SQL Injection. If you do not know what this is, have a look at http://en.wikibooks.org/wiki/PHP_Programming/SQL_Injection or do a Google search.
To get the connect.php script in action, I use the include command (think of the /copy in RPG and you are on your way).
The script is pretty straightforward.
- Connect to the database.
- Check the input.
- Build the SQL statement.
- Read the data and build an HTML table to hold the result.
- Return to caller.
Please note that if you use an asterisk (*) in the ec_load.php script, all the entries in the table will be displayed in the browser.
The last building block is the select.js, which contains the JavaScript needed to create the
select.js
//=======================================================
// JavaScript code. Source member name: selectPlan.js
//=======================================================
var xmlhttp;
// Create an instance of the XMLHttpObject
// NOTE: In all browsers except IE, this is implemented using
// the XMLHttpObject. In IE, it is implemented using an
// ActiveXObject.
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
// render or re-render the HTML
function stateChanged()
{
if (xmlhttp.readyState==4)
{
// For debug purpose
//var text = xmlhttp.responseText;
//alert(text);
document.getElementById("responseHTML").innerHTML=xmlhttp.responseText;
}
}
"Welcome To The Working Week"
Download the scripts. Place them somewhere in your document root and then point your browser to
http://localhost/ec.php. You will see the screen in Figure 5.
Figure 5: Now you can search.
Enter something in the search field (e.g., My Aim Is) and click the Search button. You will see the result as in Figure 6.
Figure 6: You have search results!
"Beyond Belief"
Buried inside my code, there's a little secret in the ec.php script. Locate these lines:
<input size="30" maxlength="50">
<!--<input size="30" maxlength="50">-->
Remove the <!-- and the --> on the onKeyUp line and insert it on the line before, like this:
<!--<input size="30" maxlength="50">-->
<input size="30" maxlength="50">
Then, in the sendRequest Javascript function, locate these lines:
// Get length of string
//if ( data.length < 3 ) return;
Remove the two slashes (//) in front of the second line so it looks like this:
// Get length of string
if ( data.length < 3 ) return;
Now you have changed the application so that when you start typing in the search field, the script will start searching the database as soon as the search string reaches a length of greater than three characters. Pretty cool, I think! Go ahead and give it a try.
"I Hope You're Happy Now"
As you can see, it's pretty easy to build some very cool and useful applications using a little PHP, some JavaScript, and a MySQL database under the hood.
You now have a secure environment where you can play around and expand your skills to meet the needs requested by more and more demanding users.
So till next time, listen to some Elvis Costello music, learn to write more PHP code, and enjoy your programming life.
LATEST COMMENTS
MC Press Online