php - Update MySQL from CSV file every day (load data is not allowed in stored procedures) -
i work in website (php language) , want update table every day csv file have write :
load data local infile 'c:/wamp/www/mywebsite/data/m5.csv' table m4 fields terminated "," lines terminated "\n" ignore 1 lines (col1,col2,col3,col4,col5)
and have create event in phpmyadmin when whant valid event, have error :
#1314 load data not allowed in stored procedures
how can update table every day csv file ?
thank you
in reference question: importing csv data using php/mysql
the solution problem might this
<?php $query = <<<eof load data infile 'c:/wamp/www/mywebsite/data/m5.csv' table m4 fields terminated ',' optionally enclosed '"' lines terminated '\n' ignore 1 lines (col1,col2,col3,col4,col5) eof; $db->query($query); ?>
however, if interested in php script same thing try this
<?php $dbhost = ""; $dbname = ""; $dbusername = ""; $dbpassword = ""; $dbtable = "m4"; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "c:/wamp/www/mywebsite/data/m5.csv"; /********************************/ /* set 1 if table have auto_increment field. /********************************/ $addauto = 0; /********************************/ /* save mysqli queries in file? if yes set $save 1. /* permission on file should set 777. either upload sample file through ftp , /* change permissions, or execute @ prompt: touch output.sql && chmod 777 output.sql /********************************/ $save = 0; $outputfile = ""; if(!file_exists($csvfile)) { echo "file not found. make sure specified correct path.\n"; exit; } $file = fopen($csvfile,"r"); if(!$file) { echo "error opening data file.\n"; exit; } $size = filesize($csvfile); if(!$size) { echo "file empty.\n"; exit; } $csvcontent = fread($file,$size); fclose($file); $conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die('could not connect'); mysqli_set_charset($conn,"utf8"); $sqldel="delete ".$dbtable; $conn->query($sqldel); $lines = 0; $queries = ""; $linearray = array(); foreach(explode($lineseparator,$csvcontent) $line) { $lines++; $line = trim($line," \t"); $line = str_replace("\r","",$line); /************************************ line escapes special character. remove if entries escaped in csv file ************************************/ $line = str_replace("'","\'",$line); /*************************************/ $linearray = explode($fieldseparator,$line); $linemysql = implode("','",$linearray); $linemysql = utf8_encode($linemysql); if($addauto) $query = "insert $dbtable values('','$linemysql');"; else $query = "insert $dbtable values('$linemysql');"; $queries .= $query . "\n"; $res_i=$conn->query($query); } if($save) { if(!is_writable($outputfile)) { echo "file not writable, check permissions.\n"; } else { $file2 = fopen($outputfile,"w"); if(!$file2) { echo "error writing output file.\n"; } else { fwrite($file2,$queries); fclose($file2); } } } ?>
Comments
Post a Comment