i want to upload my csv file to mysql db. $query = "LOAD DATA LOCAL INFILE '1.csv' INTO TABLE test FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (uid, name, tel)"; $result = mysql_query($query); Code (markup): 1.csv saved in this coding file csv. This is csv data 22,Kasun Chamara,89975954 55,Dsukfefk,5945945665 42,vewgfr,45644562162 Code (markup): but not upload to db. help me
i resolved that pro $query = "load data local infile 'c:/1.csv' into table test fields terminated by ',' lines terminated by '\n' (uid, name, tel)"; $result = mysql_query($query); but. if i send query again, get duplicate csv datas. do u knw how to update database with over righting.
i thought that. and this is my code <?php $sql = "SELECT * FROM test"; $result = mysql_query($sql); if (mysql_num_rows($result) > 0){ mysql_query("DELETE FROM test"); mysql_query("ALTER TABLE test AUTO_INCREMENT = 1"); $query = "load data local infile '/1.csv' into table test fields terminated by ',' lines terminated by '\n'(uid, name, tel)"; mysql_query($query); echo "Update Data Success"; } else{ mysql_query("ALTER TABLE test AUTO_INCREMENT = 1"); $query = "load data local infile '/1.csv' into table test fields terminated by ',' lines terminated by '\n'(uid, name, tel)"; mysql_query($query); echo "Added New Data Successful"; } ?> Thank You
Instead of using 'load data' sql query, you can use a custom CSV parser. This will allow you to easily strip duplicates and do other kind of validations. Example is as follows: $str = file_get_contents("1.csv"); $lines = explode("\n",$str); for($i=0;$i<count($lines);$i++) { list($uid,$name,$tel) = explode("," , $lines); $data = mysql_query("SELECT * FROM users WHERE uid='".$uid."' LIMIT 1"); if(mysql_num_rows($data)>0) { $query = "UPDATE users SET name='".$name."', tel='".$tel."' WHERE uid='".$uid."' LIMIT 1"; } else { $query = "INSERT INTO users (uid, name, tel) VALUES ('".$uid."', '".$name."', '".$tel."')"; } mysql_query($query); } PHP: Although, I do admit that this piece of code is much more performance costly. It'll take much more time than "load data" query.