php - Converting a text file into CSV or storing each value in mysql? -
sampnum acc_x acc_y acc_z 1 0.89304 0.00366 -0.247416 2 0.89304 0.00366 -0.247416 3 0.887184 0.008052 -0.240096
i have log file , need convert csv file or pick every field , save mysql table columns name sampnum, etc along corresponding values.
how can php?
please:
- don't use deprecated ext/mysql, when can use ext/mysqli or pdo.
- don't read entire csv file php variable. happens when file 500mb?
- don't write custom php code parse csv data, when can use builtin function fgetcsv().
- don't create new sql statement every row in data, when can use prepared statements.
- don't interpolate data external file sql statements. risks sql injection vulnerabilities, when interpolate untrusted user input.
- don't parse , insert csv data row row, when can use mysql's load data infile command. it's 20x faster inserting row row.
here's simpler solution:
<?php $databasehost = "localhost"; $databasename = "test"; $databasetable = "sample"; $databaseusername="test"; $databasepassword = ""; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "filename.csv"; if(!file_exists($csvfile)) { die("file not found. make sure specified correct path."); } try { $pdo = new pdo("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, array( pdo::mysql_attr_local_infile => true, pdo::attr_errmode => pdo::errmode_exception ) ); } catch (pdoexception $e) { die("database connection failed: ".$e->getmessage()); } $affectedrows = $pdo->exec(" load data local infile ".$pdo->quote($csvfile)." table `$databasetable` fields terminated ".$pdo->quote($fieldseparator)." lines terminated ".$pdo->quote($lineseparator)); echo "loaded total of $affectedrows records csv file.\n"; ?>
Comments
Post a Comment