Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class CSVImport {
- public $csvData;
- private $preparedData;
- function __construct($csv) {
- $delimiter = ' ';
- $quote = '""';
- $newline = "\t";
- $this -> csvData = $csv;
- print_r($csv);
- $db_quote = $quote . $quote;
- // Clean up file
- $this -> csvData = trim($this -> csvData);
- $this -> csvData = str_replace("\r\n", $newline, $this -> csvData);
- $this -> csvData = str_replace($db_quote, '"', $this -> csvData);
- // replace double quotes with " HTML entities
- $this -> csvData = str_replace(',",', ',,', $this -> csvData);
- // handle ,"", empty cells correctly
- $this -> csvData .= $delimiter;
- // Put a comma on the end, so we parse last cell
- $inquotes = false;
- $start_point = 0;
- $row = 0;
- for ($i = 0; $i < strlen($this -> csvData); $i++) {
- $char = $this -> csvData[$i];
- if ($char == $quote) {
- if ($inquotes) {
- $inquotes = false;
- } else {
- $inquotes = true;
- }
- }
- if (($char == $delimiter or $char == $newline) and !$inquotes) {
- $cell = substr($this -> csvData, $start_point, $i - $start_point);
- $cell = str_replace($quote, '', $cell);
- // Remove delimiter quotes
- $cell = str_replace('"', $quote, $cell);
- // Add in data quotes
- $data[$row][] = $cell;
- $start_point = $i + 1;
- if ($char == $newline) {
- $row++;
- }
- }
- }
- $this -> preparedData = $data;
- }
- public function testecho() {
- print_r($this -> preparedData);
- }
- public function Send_To_Database() {
- $data = $this -> preparedData;
- $host = 'localhost';
- $db = 'guestlist';
- $DBH = new PDO("mysql:host=$host;dbname=$db", "root", "");
- for ($x = 0; $x < count($data); $x++) {
- print_r($data[$x]);
- $STH = $DBH -> prepare("INSERT INTO gl_guests (listID, firstName, lastName, email, addGuests, affiliation, notes) values (:listID, :firstName, :lastName, :email, :addGuests, :affiliation, :notes)");
- $STH -> bindParam(':listID', $data[$x][0]);
- $STH -> bindParam(':firstName', $data[$x][1]);
- $STH -> bindParam(':lastName', $data[$x][2]);
- $STH -> bindParam(':email', $data[$x][3]);
- $STH -> bindParam(':addGuests', $data[$x][4]);
- $STH -> bindParam(':affiliation', $data[$x][5]);
- $STH -> bindParam(':notes', $data[$x][6]);
- $STH -> execute();
- print_r($data[$x] . "\r\n");
- $err = $STH->errorInfo();
- print_r($err);
- }
- }
- }
- ?>
Add Comment
Please, Sign In to add comment