I want to insert data from a csv file, which is already on my server into my database.
$myfile = "./files/data.csv";
Here is my connection:
class Database
{
private static $dbName = 'dbname' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'dbuser';
private static $dbUserPassword = 'dbpassword';
private static $cont = null;
public function __construct() {
exit('Init function is not allowed');
}
public static function
connect()
{
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
self::$cont->query("SET NAMES utf8");
self::$cont->query("SET CHARACTER SET utf8");
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
And this is how I insert the data into the database:
error_reporting(E_ALL); ini_set('display_errors', 1);
try {
$pdo = Database::connect();
$sql = "LOAD DATA INFILE '$myfile'
INTO TABLE `animals`
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
(id,name,animal)";
$q = $pdo->query($sql);
$q->execute();
} catch (PDOException $q) {
echo 'Connection failed: ' . $q->getMessage();
}
My csv file looks like this:
12,fred,cat,
13,tom,dog,
And this is my animals table in my database
╔════╦═════════╦════════╦════════╗
║ id ║ name ║ age ║ animal ║
╠════╬═════════╬════════╬════════╣
║ ║ ║ ║ ║
║ ║ ║ ║ ║
║ ║ ║ ║ ║
║ ║ ║ ║ ║
╚════╩═════════╩════════╩════════╝
Unfortunately it is not working, this means no data is inserted into my database. I hope you can help :)