so, I have this users list which I get it from a csv file.
What I need to do is this:
I get the file to upload, I check for each line if the user exists, if he does then all I do is update him, if he doesn’t I should create a new account for him.
I do know how to do it as a logic… but I become confused while using the csv import…
So, here it is what I use:
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into users (Username,Password,Email,first_name,last_name,phone,user_id,age,sex) values('$data[0]','".md5($data[1])."','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
What I need is something like this:
foreach (user as $data[7]) {
if user exists in user table then $query1
else $query2
}
Thanks
MySQL has a handy little function called
LOAD DATA INFILE, which allows it to load CSV files directly, without you needing to do the insert loop in PHP.You entire code could be as simple as this:
See the MySQL manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
note: I haven’t tested the above. If MySQL doesn’t have direct read access to the temp file, you may need to move it to a location the MySQL can read first, or use
LOAD DATA LOCAL INFILEinstead.note2: I’m using
mysqli_xxx()functions instead ofmysql_xx()because themysql_xx()functions are deprecated. Feel free to change it back if you need to, but be aware thatmysql_xx()is not recommended for use. I suggest you change all yourmysql_xx()calls tomysqli_xxx()as soon as convenient.