Advertisement
dsmithhayes

Copy & Paste CSV Parsing

Apr 25th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.76 KB | None | 0 0
  1. <?php
  2. # Script to parse CSV and run each
  3. # line as its own query
  4.  
  5. //assuming you have connected to the database
  6. //and the form as been submitted
  7.  
  8. $lines = explode("\n", $_POST['csv']);
  9.  
  10. $i = 0;
  11. $tally = 0;
  12. while($line = $lines[$i]){
  13.     $split = str_getcsv($list, ',', '"');
  14.  
  15.     //arbitrary variable names for examples
  16.     list($id, $name, $salary, $bonus) = $split;
  17.  
  18.     $q = mysql_query("INSERT INTO users (id, name, salary, bonus)
  19.               VALUES (".$id.", \"".$name."\", ".$salary.", ".$bonus."")
  20.               or die(mysql_error());
  21.  
  22.     //for what ever reason it doesn't work,
  23.     //it should give you an error anyways.
  24.     if(!$q){
  25.         echo "Error inserting into the database.";
  26.     }else{
  27.         $tally++;
  28.     }
  29.  
  30.     $i++;
  31. }
  32.  
  33. echo "Total of ".$tally." entries were successful.";
  34.  
  35. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement