<?php
/**
 * Parse census data file 'ustracts2k.txt'.
 * Create and fill `census_data` table.
 *
 * @author Vladimir N. Jhulyev aka JVN
 * @since	2004-02-14
 */

////////////////////////////////////////
//Configuration's variables & constants
////////////////////////////////////////

//Offset & lenght of column for state abbr
$scol = array
(
	'offs' => 0,
	'len' => 2
);

//Offset & lenght of column for population
$pcol = array
(
	'offs' => 13,
	'len' => 9
);

//Output file's name
define('FOUT', 'census.csv', FALSE);

//MySQL data
$mysql_data = array
(
	'host'   => 'localhost',
	'base'   => 'test',
	'user'   => 'root',
	'passwd' => ''
);

////////////////////////////////////////

error_reporting(E_ALL);

$dn = dirname($_SERVER['PATH_TRANSLATED']).'/';
$outf = $dn.FOUT;

($r = fopen($outf, 'w')) || die();
($h = fopen ($dn.'ustracts2k.txt', 'r')) || die();

set_time_limit(0);
ob_implicit_flush();

echo 'Start parsing...<br>';
while (!feof($h)) 
{
	$b = fgets($h);
	fwrite($r, substr($b, $scol['offs'], $scol['len'])."\t".trim(substr($b, $pcol['offs'], $pcol['len']))."\n")
		|| die('Error of fwrite()<br>');
}
@fclose ($h);
fclose ($r) || die('Error of fclose()');
echo 'End parsing succesfully<br>';

echo 'Start loading...<br>';
($m = mysql_connect($mysql_data['host'], $mysql_data['user'], $mysql_data['passwd'])) || die();
mysql_select_db($mysql_data['base'], $m) || die();
mysql_query('
	DROP TABLE IF EXISTS `census_data`
', $m) || die();
mysql_query('
	CREATE TABLE `census_data`
	(
		`state` CHAR(2) NOT NULL,
		`population` INT UNSIGNED NOT NULL,
		KEY(`state`)
	)
', $m) || die();
mysql_query("
	LOAD DATA INFILE '$outf'
	INTO TABLE `census_data`
	(`state`, `population`)
", $m) || die();
echo 'End loading succesfully<br>';

mysql_close($m);
unlink($outf);

?>
