Utklippstavle

Legg inn en helt ny kode

Valgmuligheter

DavidS sendte inn denne php-koden 25.02.2010 kl. 13:26.

<?php
/**
 * Request zip code or place from database
 * based on result from AJAX
 * 
 * @author		David Steinsland
 * @url			http://davidsteinsland.net
 * @license		Creative Commons Attribution-Share Alike 3.0 Unported License
 * @license url	http://creativecommons.org/licenses/by-sa/3.0/ 
 */
header ('Content-type:text/html;charset=utf-8');
 
if (!isset ($_GET) || !sizeof ($_GET)) {
	header ("HTTP/1.0 404 Not Found");
	die ();
}
 
// Retrieve and validate the input.
$Query = (isset ($_GET['q'])) ? utf8_decode (utf8_encode(mb_strtoupper ($_GET['q']))) : FALSE; 
 
if (!$Query) {
	header ("HTTP/1.0 404 Not Found");
	die ();
}
 
$Cache = 'cache/' . md5 ($Query) . '.txt';
 
// stores cache for 24 hours
if (file_exists ($Cache) && (time() - filemtime($Cache)) < 86400) {
	echo file_get_contents ($Cache);
	die;
}
 
// Connect to the MySQL database.
mysql_connect ('localhost', 'root', '');
mysql_select_db ('postnummer');
 
// Tell MySQL to use UTF-8.
mysql_query ("SET NAMES 'utf8'");
 
// Check if it's set correctly.
if (is_numeric ($Query) && strlen ($Query) == 4) {
	$Where = 'z.zip = ' . $Query;
} else {
	$Where = 'p.name = "' . $Query . '"';
}
 
// Run the query against the database.
$SQL = "SELECT c.name as fylke, m.name as kommune, p.name as poststed, z.zip, z.lat, z.lon
FROM zip_places p 
INNER JOIN zip_codes z ON z.place_id = p.place_id
INNER JOIN munincipial m ON m.id = p.munincipial_id
INNER JOIN county c ON c.county_id = m.county_id
WHERE $Where LIMIT 1";
$Res = mysql_query ($SQL);
 
if (mysql_num_rows ($Res) == 0) {
	header ("HTTP/1.0 404 Not Found");
	die ();
}
 
// Fetch the result.
$Data = mysql_fetch_assoc ($Res);
 
$JSON = json_encode($Data);
file_put_contents ($Cache, $JSON);
 
echo $JSON;
?>

Tilbake til toppen ^

Emneord (tags): php, postal, ajax, postnummer