Skip to content

Instantly share code, notes, and snippets.

@noomz
Created October 22, 2011 17:17
Show Gist options
  • Save noomz/1306239 to your computer and use it in GitHub Desktop.
Save noomz/1306239 to your computer and use it in GitHub Desktop.
thaiflood events fetch
<?php
error_reporting(E_ALL ^ E_NOTICE);
define('EVENTTABLE', 'events');
// Config
$dbconfig = array(
'host' => 'localhost',
'user' => 'root',
'pass' => 'qwer',
'db' => 'floodevents',
);
$db = mysql_connect($dbconfig['host'], $dbconfig['user'], $dbconfig['pass']);
if (!$db) {
die('Can\'t connect to db.');
}
mysql_set_charset('utf8');
mysql_select_db($dbconfig['db']);
// Auto-create table.
$result = mysql_query("SHOW TABLES LIKE '". EVENTTABLE ."'");
if (mysql_num_rows($result) === 0) {
$result = mysql_query("
CREATE TABLE IF NOT EXISTS `". EVENTTABLE ."` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`lat` float NOT NULL,
`lon` float NOT NULL,
`address` varchar(255) NOT NULL,
`message` varchar(255) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`hash` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`),
KEY `updated_at` (`updated_at`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5201 ;
");
if (!$result) {
die('Can\'t create table');
}
}
$json = file_get_contents('http://thaiflood.heroku.com/events/latest.json?limit=1000');
if (!$json) {
die('Can\'t get data.');
}
$events = json_decode($json);
foreach ($events as $key => $event) {
$hash = md5(sprintf("%f%f%s%s", $event->lat, $event->lon, $event->message, $event->updated_at));
$sql = sprintf("INSERT INTO ". EVENTTABLE ." (lat, lon, address, message, created_at, updated_at, hash) VALUES (%f, %f, '%s', '%s', '%s', '%s', '%s')", $event->lat, $event->lon, $event->address, $event->message, $event->created_at, $event->updated_at, $hash);
print "Inserting row: $key ...\n";
$result = mysql_query($sql);
if (!$result) {
die("Insert failed : ". mysql_error() ."\n");
}
}
mysql_close($db);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment