Utklippstavle

Legg inn en helt ny kode

Valgmuligheter

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

  1. <?php
  2. /**
  3.  * Request zip code or place from database
  4.  * based on result from AJAX
  5.  *
  6.  * @author David Steinsland
  7.  * @url http://davidsteinsland.net
  8.  * @license Creative Commons Attribution-Share Alike 3.0 Unported License
  9.  * @license url http://creativecommons.org/licenses/by-sa/3.0/
  10.  */
  11. header ('Content-type:text/html;charset=utf-8');
  12.  
  13. if (!isset ($_GET) || !sizeof ($_GET)) {
  14. header ("HTTP/1.0 404 Not Found");
  15. die ();
  16. }
  17.  
  18. // Retrieve and validate the input.
  19. $Query = (isset ($_GET['q'])) ? utf8_decode (utf8_encode(mb_strtoupper ($_GET['q']))) : FALSE;
  20.  
  21. if (!$Query) {
  22. header ("HTTP/1.0 404 Not Found");
  23. die ();
  24. }
  25.  
  26. $Cache = 'cache/' . md5 ($Query) . '.txt';
  27.  
  28. // stores cache for 24 hours
  29. if (file_exists ($Cache) && (time() - filemtime($Cache)) < 86400) {
  30. die;
  31. }
  32.  
  33. // Connect to the MySQL database.
  34. mysql_connect ('localhost', 'root', '');
  35. mysql_select_db ('postnummer');
  36.  
  37. // Tell MySQL to use UTF-8.
  38. mysql_query ("SET NAMES 'utf8'");
  39.  
  40. // Check if it's set correctly.
  41. if (is_numeric ($Query) && strlen ($Query) == 4) {
  42. $Where = 'z.zip = ' . $Query;
  43. } else {
  44. $Where = 'p.name = "' . $Query . '"';
  45. }
  46.  
  47. // Run the query against the database.
  48. $SQL = "SELECT c.name as fylke, m.name as kommune, p.name as poststed, z.zip, z.lat, z.lon
  49. FROM zip_places p
  50. INNER JOIN zip_codes z ON z.place_id = p.place_id
  51. INNER JOIN munincipial m ON m.id = p.munincipial_id
  52. INNER JOIN county c ON c.county_id = m.county_id
  53. WHERE $Where LIMIT 1";
  54. $Res = mysql_query ($SQL);
  55.  
  56. if (mysql_num_rows ($Res) == 0) {
  57. header ("HTTP/1.0 404 Not Found");
  58. die ();
  59. }
  60.  
  61. // Fetch the result.
  62. $Data = mysql_fetch_assoc ($Res);
  63.  
  64. $JSON = json_encode($Data);
  65. file_put_contents ($Cache, $JSON);
  66.  
  67. echo $JSON;
  68. ?>

Tilbake til toppen ^

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