Archive for the ‘PHP’ Category

Google Maps API part 2: Retrieving Postcodes from your database

googlemaps part2

OK, this is a simple way to get your postcode/ address location returned and displayed via the Google Maps API on your own website. I’ll cover the ‘nearest store locator’ scenario in another post where you want places with a certain radius of an inputted postcode/ town returned.

First of all we need to retrieve our results which should already be stored with a geocoded result using the previous tutorial here. remember that in order for this to work you need an API key from google – again check the previous tutorial for more info on this.

We’re going to need to pass the geocoded values retrieved from the database into javascript and there are a few ways of doing this. This is really the hardest part and the only work you really need to do to display your result on a map as the Google maps API does the rest of the work for you. So we can either do this via something like an AJAX request whereby you build your returned data into an XML file and then use javascript to read that. Or you can write your php inline inside the javascript, which is messy for multiple results but in the singular it should be fine.

First lets start with the chunk of javascript on the page that will display our map etc… This method just calls up a map from the API and then zooms, centers and adds a marker to a specified co-ordinate. This singular display is useful if you want to, for instance, display the location of a result in a popup/ overlay.

// your API key here.

To see the map just add in a HTML element and set an onload event assigned to your body tag as thus

So now we just need to pass in our result from the database. Starting with passing it inline to javascript variable we can do the following, first connect and get your results from your database, very basically as below.

 LIMIT 1");

// assign the results to variables something like:
while ($row = @mysql_fetch_assoc($result)){
$lat = $row['lat'];
$lng = $row['lng'];

Ok, so in javascript we can then put in our php values:

// declare variable to store co-ordinates - fetch these from your database

// var coords = new GLatLng(51, -1);
// or you can do this:
// var coords = new GLatLng(, );

So all together the php page will look something like this:

 LIMIT 1");

// assign the results to variables something like:
while ($row = @mysql_fetch_assoc($result)){
$lat = $row['lat'];
$lng = $row['lng'];

For retrieving the results via an XML file instead I’ll cover that in part 3 as its much more applicable there.

Google Maps API part 1: Accurate Geocoding for UK Postcodes


Recently I had to build a system that would take an address, pass it to google and return latitude and longitude values. The result is then stored for later use and display on Google maps.

However, firstly I found that the default XML geocoding service provided by Google that allows you to do bulk geocoding on a data source and the geocoding provided by their maps API/ AJAX library (GClientGeocoder) had huge differences in results. Most postal codes passed to googles XML geocoding service were miles out or just not recognised. Yet when using the same postcode in the maps API when calculated on the fly the results were more or less spot on.

You can take a look at a tutorial for using Googles XML geocoder service, PHP and MySQL here. They suggest that this way is good if you don’t want to repeatedly geocode the same address again and again and if you want to do bulk geocoding.

Which would be nice, if it was actually accurate! But this still leaves me with having to do bulk uploads or geocoding and get accurate results to build, for instance, a store locator around the data.

The solution is simple, we can utilise the Google maps API to do the geocoding for us on the fly and store the result passed back using some simple AJAX to send the data to PHP/ MySQL. While I geocode my records at the time of their entry, in the example below, you could just as easily use this to create some sort of bulk update. Check out my tutorial here about using AJAX to pass form data to PHP if you’re new to this.

Firstly you will need to signup to get a couple of free API keys from google, you don’t require much to get them and they’ll work just fine for a localhost.

Maps API key:
AJAX Search API key:

OK so now we create a HTML page, form.htm, this will call in the Javascript libraries and do the geocoding work.

We also build a function that creates an XML object in the DOM to store the data, which will then get passed to the PHP page. This works in exactly the same way as my tutorial here.

This chunk of code above is what utilises the google maps keys, to pass the data to google, geocode it and return the record and I've written this inside of a function that gets called on the form submission, which in turn then uses the previously declared XML creation function.

The final stage of this HTML page is of course the form which sends the data and a span tag that displays the results if successful.

Address Line 1:
Address Line 2:
Address Line 3:


This then just leaves us the PHP page (post.php) that will then post the results, again nothing too disimilar to my previous tutorials on this. This is the bit where you would pass in the $_POST parameters and store them using MySQL etc... or save them to a text file.

And there we have it, accurate geocoding from google that can be used as a service when data is entered, or you could use this same method by passing in XML created from your database and iterating over this passing each result to the API and returning a value.

Now you can build a store locator or whatever that actually returns accurate results, also you can then use this to integrate your database better with the full Google maps API - showing maps, placing markers on maps etc..

Using Javascript/ AJAX to post HTML form data

javascript form ajax php

Why would you need to do this? Well for instance if you were using 3rd party AJAX APIs and you wanted to capture the data from them perhaps, or maybe you just have a complex form.

Or you could use this for form validation to return errors from the server without refreshing the browser, for example, if the data already exists in a database you could let the user know.

Either way its pretty simple. Basically we just use javascript to post the form object over http to a serverside page – e.g. PHP, JSP, ASP etc…

First of lets have a look at the javascript

And thats it, as for the HTML form, only thing to note is that the form action calls the sendData function:

* Address Line 1:
Address Line 2:
Address Line 3:
* Town:
* Postcode:

Oh and of course the post.php page, in here you could add in your validation, check the database etc... what ever you ourput to the page (using print, echo etc...) can be then sent back to your form page and displayed without the user leaving your form page or refreshing the browser.

Upload a File Using PHP


Ok so you want to upload a file to your webspace. Easy enough you just need some sort of server-side language. In this case it’s PHP, this tutorial should work with versions 4 upwards.

So we’ll build just 1 file to handle the upload, display status and the form.

Im going to call this upload0r.php (you can call it whatever you want)

First of all make a folder in your webspace/server called uploads, by default it should have read, write and execute permissions (chmod 777) if it doesn’t you can use something like Filezilla FTP client to alter this.

The PHP we use revolves around a few inbuilt functions in the standard PHP libraries – I’ve linked these to the relevant PHP info pages for you to read more.

The first is the $_FILES array, this is a super global variable used soley to store uploaded content from a form and details about the file you upload. It expects two parameters to be passed when using it.

The first parameter comes from your form’s input name. So for example in my form I have the following field:

<- note the type!

So when using $_FILES to refer to this upload I set the first parameter as:


The second part can then be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

The name of the file sent via your form

The type of the file, e.g jpeg, gif – note we dont need to look at the extension as this data also resides in the files metadata.

The size in bytes of your file

The name of the temporary copy of the file stored on the server. Generally you shouldn’t need to set your tmp directory but just in case a good starting point is the php.ini file.

Any error code resulting from the file being uploaded

So using this we can write some very quick validation around to help reduce malicious use, of course you should also write validation around you form entry to sanitise the input. So for example:

if ((($_FILES[“uploadThisFile”][“type”] == “image/gif”) //check the file type
|| ($_FILES[“uploadThisFile”][“type”] == “image/jpeg”))    //add in as many checks as you want
&& ($_FILES[“uploadThisFile”][“size”] < 100000)) { //check the filesize is less than 100kb

//check the $_FILES array for errors
if ($_FILES[“uploadThisFile”][“error”] > 0) {

So I check for the file types I want, and if there were any errors before saving the file to my webspace.

Using another inbuilt PHP function I can quickly check to see if the file already exists:

if (file_exists(“uploads/” . $_FILES[“uploadThisFile”][“name”])) {

This function takes only one parameter which is the location of a file on the server and checks to see if its there or not returning true or false.

And the final function, again provided with PHP is move_uploaded_file() which is only for moving a file thats been uploaded to the tmp directory and then moving it and renaming it to a specified destination as thus:

move_uploaded_file($_FILES[“uploadThisFile”][“tmp_name”], “uploads/” . $_FILES[“uploadThisFile”][“name”]);

And thats basically it, so heres the final code below with some comments:

//set a variable to store the status of the upload
$status = “”;

// could write the filetypes as an array to be checked.

if ((($_FILES[“uploadThisFile”][“type”] == “image/gif”) //check the file type
|| ($_FILES[“uploadThisFile”][“type”] == “image/jpeg”))    //add in as many checks as you want
&& ($_FILES[“uploadThisFile”][“size”] < 100000)) { //check the filesize is less than 100kb

//check the $_FILES array for errors
if ($_FILES[“uploadThisFile”][“error”] > 0) {

$status .= “There were the following errors during the upload: ” . $_FILES[“uploadThisFile”][“error”] . “

} else {

//check if the file already exists by using file_exists() function and tell user
if (file_exists(“uploads/” . $_FILES[“uploadThisFile”][“name”])) {

$status .= $_FILES[“uploadThisFile”][“name”] . ” already exists. “;

} else {

//use move_uploaded_file to move the temporary item to your directory
move_uploaded_file($_FILES[“uploadThisFile”][“tmp_name”], “uploads/” . $_FILES[“uploadThisFile”][“name”]);

//tell user that file was uploaded, what it was etc..
$status .= “File uploaded: ” . $_FILES[“uploadThisFile”][“name”] . “
$status .= “File Type: ” . $_FILES[“uploadThisFile”][“type”] . “
$status .= “File Size: ” . ($_FILES[“uploadThisFile”][“size”] / 1024) . ” Kb
$status .= “Stored in: ” . “uploads/” . $_FILES[“uploadThisFile”][“name”].”“;

/* you could write a database routine to stuff in this data and record
mysql_query(INSERT INTO VALUES (”, ‘$_FILES[“uploadThisFile”][“name”]’);

} //end if file exists check and user confirmation

} //end if errors in upload check

} else {

//if the file type isn’t one specified in the first if statement
$status .= “Invalid file, should be gif or jpeg”;

} //end if

echo $status;


$_SERVER[‘PHP_SELF’] //posts back to its self ?>” method=”POST”>
Choose a file to upload:

Creating XML from PHP/ MySQL for use with SPRY

So lets say for example you have a table in your database and you want to return some results, pretty easy with PHP/ MySQL and I dare say easy enough with other languages.

Now rather than return the results to the page and format them etc… you want to instead put them to an XML file – why? Well because creating a dataset in XML allows you to make use of various things both from a design point of view and from the prespective of user interaction. I’m of course talking about AJAX here (but also useful for XSLT etc…).

So assuming you are using PHP5, MySQL5 you can use the template below to do this. I’ve also used Adobe’s SPRY here, but jQuery or straight forward Javascript is easy enough. I’m going to assume you are also using SPRY – but there’s an example at the bottom using plain old javascript.

First stage: Create PHP page to build XML from database query

So this is my page: queryBuilder.php

It takes a parameter parsed via the URL GET method (q) and then loads the data based on this. Using this you can create a lot of different XML datasets served from just one page. Replace [text] with your own values.

createElement(‘[parent node]’);
$root = $doc->appendChild($root);
//create a document header to tell browsers what type of file this is
header(“Content-type: text/xml”);
//fetch data from your database table
$myList = mysql_query(“SELECT
ID,  Name
FROM mytable
// process one row at a time
while ($row = mysql_fetch_assoc($myTrades)) {

// add node for each row
$occ = $doc->createElement(‘[child node name]’);
$occ = $root->appendChild($occ);

// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} // end foreach
} // end while

// get completed xml document
$xml_tradesList = $doc->saveXML();
//return xml page to the browser
echo $xml_tradesList;
} //end if q=

} //end if isset

//close db connection

Second stage: Create page to filter and display data.

So we can now fetch our dataset and use some javascript/AJAX call to get the XML. For simplicity I’m going to use SPRY, Adobes library, but you can just as easily use jQuery.

Creating a page called queryBuilder.htm first thing is to add in the framework libraries that you need available from Dreamweaver install or free from Adobes site (as linked):

Next we need to define our datasets – if you’re used to SPRY this should be easy enough for you.

So thats essentially it, SPRY calling in records from your database via a PHP page. Of course I’m assuming that you know how to display records in SPRY? No? Well here’s how to do it quickly for a select menu!

//declare a region for SPRY

//declare a region that will repeat all results in a loop

Easy huh?

Alternative to SPRY do it in Javascript

So with just Javascript a chunk of code such as below will do much the same thing as the SPRY code just you have to write more.

Make a file queryBuilder.js

//create variable to store the output of queryBuilder.php
var xmlhttp

// function to create an XML object
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;

function showList(str)
xmlhttp=GetXmlHttpObject(); //function defined below
if (xmlhttp==null)
alert (“Your browser does not support AJAX!”);
var url=”queryBuilder.php”;
//this fetches the XML data in the DOM from the queryBuilder.php page

function stateChanged()
//if XML has been loaded and is ready
if (xmlhttp.readyState==4)
// display the xml from queryBuilder.php to this HTML element
document.getElementById(“[Some HTML element]”).innerHTML=xmlhttp.responseText;

So now you can include this on your html page and call in the XML by calling the js function showList([data to load])