<?php // RAY_temp_imaginx.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;
// DEMONSTRATE HOW TO LOAD A CSV FILE INTO A DATA BASE
$csv = 'RAY_imaginx_data.csv';
// SAMPLE DATA LOOKS LIKE THIS
// NOTE TRAILING COMMA - PROBABLY AN ERROR - ARTIFACT OF SAVING FROM MICROSOFT EXCEL
// NOTE THE DATE FORMAT - VALID IN PHP, BUT NOT VALID IN MySQL
// 1...5...10...15...20...25...30...35...40...45...
// Vera,Aguirro,,Criselda,regular,1/1/2010,
// 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
// CREATING THE TABLE
$sql = "CREATE TEMPORARY TABLE t
(
a VARCHAR(20) NOT NULL,
b VARCHAR(20) NOT NULL,
c VARCHAR(20) NOT NULL,
d VARCHAR(20) NOT NULL,
e VARCHAR(20) NOT NULL,
f DATE NOT NULL
) ENGINE=MEMORY";
$res = mysql_query($sql) or die( mysql_error() );
// READING THE CSV FILE AND LOADING THE TABLE
$fp = fopen($csv, 'r');
while (!feof($fp))
{
// READ THE CSV DATA INTO AN ARRAY
$arr = fgetcsv($fp);
if ($arr)
{
// DISCARD THE USELESS NULL STRING CAUSED BY THE TRAILING COMMA
array_pop($arr);
// CONVERT THE INVALID DATE FORMAT TO THE ISO FORMAT
$arr[5] = date('c', strtotime($arr[5]));
// CREATE THE INSERT QUERY
$sql = 'INSERT INTO t ( a, b, c, d, e, f ) VALUES (';
// APPEND THE DATA FIELDS TO THE INSERT QUERY
foreach ($arr as $val)
{
$val = "'" . mysql_real_escape_string($val) . "'" . ',';
$sql .= $val;
}
// FINISH THE INSERT QUERY
$sql = rtrim($sql, ',');
$sql .= ')';
var_dump($sql);
// RUN THE QUERY
if (!$res = mysql_query($sql)) die( mysql_error() );
}
}
// EXAMINING THE TABLE TO SEE THE DATA WE LOADED
$res = mysql_query('SELECT * FROM t');
while ($row = mysql_fetch_assoc($res))
{
var_dump($row);
}
|