<?php // RAY_csv_to_db.php
error_reporting(E_ALL);
echo "<pre>\n"; //READABILITY FOR var_dump()
// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??"; // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";
// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>NO DB CONNECTION: ";
echo "<br/> $errmsg <br/>";
}
// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>NO DB SELECTION: ";
echo "<br/> $errmsg <br/>";
die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES
// THE NAMES OF OUR COLUMNS
$query_cols = "name, price, Description";
// TEST DATA URL
$csv = "http://path/to/my.csv";
$fpo = fopen($csv, 'r');
if (!$fpo ) die('CRUMP');
// SET A ROW COUNTER
$counter = 0;
// KEEP TRACK OF ROWS THAT HAVE THE WRONG NUMBER OF FIELDS
$errors = array();
// LOOP THROUGH THE CSV RECORDS PERFORMING CERTAIN TESTS
while (!feof($fpo))
{
$counter++;
// GET A RECORD
$csvdata = fgetcsv($fpo);
// SKIP OVER EMPTY ROWS
if (empty($csvdata)) continue;
// ESCAPE THE INFORMATION FOR USE IN THE QUERY
foreach ($csvdata as $ptr => $value)
{
$csvdata[$ptr] = mysql_real_escape_string($value);
}
// SET UP VALUE FIELDS
$query_data = "'" . implode("', '", $csvdata) . "'";
// SET UP A QUERY
$sql = "REPLACE INTO myTable ( $query_cols ) VALUES ( $query_data )";
// RUN THE QUERY HERE....
$res = mysql_query($sql);
// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php
if (!$res)
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>QUERY FAIL: ";
echo "<br/>$sql <br/>";
die($errmsg);
}
}
// SHOW THE NUMBER OF ROWS PROCESSED
echo "<br/>RECORDS PROCESSED $counter \n";
|