Re: Parse a text file?
Posted: Thu Jan 15, 2009 2:09 pm
In that case you'd have to do something like this:
Hope that helps.
Code: Select all
<?php
// set this constant to 'true' to toggle detailed output
define("DEBUG", false);
// location of the pipe separated values file
static $psv = "./data.psv";
// mysql config
static $mysql_server = "your-server.com";
static $mysql_database = "your-database-name";
static $mysql_user = "your-username";
static $mysql_password = "your-password";
static $mysql_table = "your-table-name";
// variable declaration for mysql aux. fxn.s:
$mysql_connect;
function make_db_cxn() {
global $mysql_connect, $mysql_server, $mysql_database, $mysql_user, $mysql_password;
/* ERROR 1 */
DEBUG ? $mysql_connect = mysql_connect("$mysql_server", "$mysql_user", "$mysql_password") or die("<br /><br />Error 1: Unable to connect to DB Server.<br />".mysql_error()) : $mysql_connect = mysql_connect("$mysql_server", "$mysql_database", "$mysql_password") or die("<br /><br />Error 1: Unable to connect to DB Server.<br />");
/* ERROR 2 */
DEBUG ? $selected = mysql_select_db("$mysql_database", $mysql_connect) or die("<br /><br />Error 2: Unable to select the database.<br />".mysql_error()) : $selected = mysql_select_db("$mysql_database", $mysql_connect) or die("<br /><br />Error 2: Unable to select the database.<br />");
}
function close_cxn() {
global $mysql_connect;
mysql_close($mysql_connect);
}
$psv_recs = file($psv, FILE_IGNORE_NEW_LINES);
$q = "INSERT INTO $mysql_table (";
foreach(explode('|', array_shift($psv_recs)) as $field) {
$q .= $field.",";
}
$q = rtrim($q, ",");
$q .= ") VALUES ";
foreach($psv_recs as $raw_rec) {
$rec = explode('|', $raw_rec);
$q .= "(";
foreach($rec as $field_val) {
$q .= "'$field_val',";
}
rtrim($q, ",");
$q .= "),";
}
$q = rtrim($q, ",");
$q .= ";";
make_db_cxn();
mysql_query($q);
close_cxn();
?>