Casuale ramblings tecnologia
19 Feb
Si tratta di un semplice script che vi permetterà di importare i dati csv nel database. Questo è particolarmente utile perché si può semplicemente modificare i campi appropriati, caricarlo con il file csv e lo chiamano dal web e lo farà il resto.
Esso consente di specificare il delimitatore in questo file csv, se si tratta di una virgola, un ecc scheda Permette anche di scegliere il separatore di linea, consente di salvare l'output in un file (conosciuto come un dump dei dati sql).
Permette inoltre di inserire un campo vuoto all'inizio di ogni riga, che è solitamente un incremento automatico intero chiave primaria.
Questo script è utile soprattutto se non avete phpmyadmin, o non vuoi la seccatura di login e di preferire una soluzione di pochi clic, o semplicemente sono un ragazzo prompt dei comandi.
Basta assicurarsi che il tavolo è già stato creato prima di tentare di eseguire il dump dei dati.
Si prega di inviare i tuoi commenti se hai un bug report.
135 Risposte per "script PHP per importare i dati csv in mysql"
Molto utile, grazie.
Io di solito uso phpmyadmin, ma vero, nel caso in cui non si ha installata, e non ha accesso alla shell (come la maggior parte dei provider di hosting condiviso), questo può rivelarsi molto utile.
Grazie mille questa risparmiato un sacco di tempo! Script di Nizza.
[...] Ebbene, oggi voglio presentarvi un altro metodo per ottenere il vostro file csv in sql, utilizzando il codice PHP. Per questo pezzo di codice, il merito va a pieno leggenda. È necessario assicurarsi che il database è già creato prima di scaricare la data. /************************************************* *******************************************/ / Code * a http: / / legend.ws / blog / consigli-trucchi / csv-php-mysql-import / / * Modifica le voci qui sotto per riflettere i valori appropriati /****************** ************************************************** ************************/ databasehost $ = "localhost"; databasename $ = "test"; $ DATABASETABLE = "campione"; databaseusername $ = " prova "; databasepassword $ =" "; fieldseparator $ =" "; $ lineseparator =" n "; $ csvfile =" bbqrest.csv "; /***************** ************************************************** *************************/ / * Vuoi aggiungere un campo ampty all'inizio di questi record? / * Questo è utile se si dispone di una tabella con il primo campo è un intero auto_increment / * e il file csv non ha come campo vuoto prima del record. / * Set 1 per sì e 0 per il no. ATTENZIONE: non impostato a 1 se non siete sicuri. / * Questo può scaricare i dati nei campi sbagliato se questo campo aggiuntivo non esiste nella tabella /***************************** ************************************************** *************/ $ addauto = 0; /****************************** ************************************************** ************/ / * Volete salvare le query mysql in un file? Se sì impostare $ risparmiare a 1. / * Autorizzazione sul file deve essere impostato a 777. O caricare un file di esempio tramite FTP e / * cambiare i permessi, o eseguire al prompt: tocco output.sql & & chmod 777 output.sql /******************* ************************************************** ***********************/ risparmiare $ = 1; $ outputfile = "output.sql"; /*********** ************************************************** *******************************/ [...]
Ciao a tutti, una piccola modifica per i valori di incremento automatico nella colonna 1 (campo id)
vedere la variabile $ count.
ola, enrico.
/ / $ Con = @ mysql_connect ($ databasehost, databaseusername $, $ databasepassword) or die (mysql_error ());
/ / @ Mysql_select_db ($ databasename) or die (mysql_error ());
$ Righe = 0;
$ Query = "";
$ Linearray = array ();
$ Count = 0;
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$ Count = $ count + 1;
$ Righe + +;
$ Riga = trim ($ riga, "\ t");
$ Linea = str_replace ("'"," \ '", $ line);
$ Linearray = explode ($ fieldseparator, $ line);
$ Linemysql = implodere ("','",$ linearray);
$ Query = "INSERT INTO` la tua tabella db `VALUES ('$ count', '$ linemysql');";
$ Query .= $ query. "\ N";
@ Mysql_query ($ query);
}
/ / @ Mysql_close ($ con);
[...] Su una nota simile, ecco un script prefabbricato, che il suo autore si dice importare un file CSV in MySql: script PHP per importare i dati csv in mysql. [...]
[...] /******************************************** ************************************************/ / * Codice di https://legend.ws/blog/tips-tricks/csv-php-mysql-import/ / * Modificare le voci qui sotto per riflettere i valori appropriati /************* ************************************************** *****************************/ databasehost $ = "localhost"; $ databasename = "xxxxx"; $ DATABASETABLE = "xxxx" ; $ databaseusername = "xxxx"; $ databasepassword = "xxxx"; fieldseparator $ = ""; $ lineseparator = "n"; $ csvfile = "xport/2008_BF.csv"; /********* ************************************************** *********************************/ / * Vuoi aggiungere un campo ampty all'inizio di questi record ? / * Questo è utile se si dispone di una tabella con il primo campo è un intero auto_increment / * e il file csv non ha come campo vuoto prima del record. / * Set 1 per sì e 0 per il no. ATTENZIONE: non impostato a 1 se non siete sicuri. / * Questo può scaricare i dati nei campi sbagliato se questo campo aggiuntivo non esiste nella tabella /***************************** ************************************************** *************/ $ addauto = 0; /****************************** ************************************************** ************/ / * Volete salvare le query mysql in un file? Se sì impostare $ risparmiare a 1. / * Autorizzazione sul file deve essere impostato a 777. O caricare un file di esempio tramite FTP e / * cambiare i permessi, o eseguire al prompt: tocco output.sql & & chmod 777 output.sql /******************* ************************************************** ***********************/ risparmiare $ = 1; $ outputfile = "output.sql"; /*********** ************************************************** *******************************/ [...]
Wow ... è fresco aveva idea dopo aver letto il tuo codice ... ringrazio molto
Newbie totale - strappandomi i capelli tentando di importare Excel CSV in phpMyAdmin (su un Mac). Mi piacerebbe sapere esattamente dove e cosa devo fare con questo script php ...?
Steve,
Si sarebbe posto questo script in una cartella accessibile sul web, dopo aver cambiato le variabili che devono essere cambiati. Leggi i commenti nello script per scoprire che cosa è necessario specificare. Poi, chiamare lo script in un browser web, come:
https://www.example.com/path-to-script/simplescvimport.php
sarebbe una buona idea aggiungere prevenire intestazioni all'interno del CSV di essere presentate nel database. Oppure, per creare uno script che tira fuori la prima fila e crea un db utilizzando questi valori come i nomi delle colonne.
Ricevo questo errore file non trovato. Assicurati di specificare il percorso corretto.
Può uno veloce risposta ho un file csv a bbqrest.csv percorso corretto (root) ..
Rengaraj,
il file csv dovrebbe essere nello stesso posto del file PHP.
Inoltre, non hanno davvero a utilizzare lo stesso nome del file csv.
bbqrest.csv è un esempio, sostituire il nome del file con il vostro.
Non tiene conto per i campi come questa riga:
Fname, Lname "Società, Inc", Città, Stato, CAP
Società e ottenere Inc diviso in due colonne diverse.
Bene, ecco la correzione al mio commento precedente:
inserire questo tra:
$ Linearray = explode ($ fieldseparator, $ line);
... Inserire il frammento di codice qui sotto ....
$ Linemysql = implodere ("','",$ linearray);
Trova e mantiene tutti "Stuff, più cose" insieme prima di implodere esso.
$ A = "";
$ B = "";
$ Qoutecount = 0;
for ($ x = 0; $ x -1) {
$ Qoutecount + +;
if ($ qoutecount == 1)
$ A = $ x; / / store prima istanza
elseif ($ qoutecount == 2) {
$ Quotecount = 0;
$ B = $ x / / memorizzare la seconda istanza
/ / CHE FA ... compilare tutti gli elementi da $ a $ b in $ a ignorare gli elementi e tutto ciò dopo che $ a $ b nel nuovo array;
Newa $ = ""; / / inizializzare nuova stringa.
for ($ z = $ a, $ z $ a & & $ y
)
/ / Salta perché rientra in elementi dell'array male
altro
$ NuovoArray [$ y] = str_replace ('"',",$ linearray [$ y]);
$ Linearray = array_values ($ nuovoArray); / / reset le chiavi del nuovo array
$ X + +;
}
}
}
ottengo il primo nella misura in cui tagliare e il resto solo codice nel browser. So che php sta lavorando perché il resto del sito funziona.
Ho fatto l'aggiornamento a php5 che importa?
brad, se l'avesse scaricato in precedenza che la scorsa settimana, sostituire il '<?' in alto con '<? php' (togliere spazio)
Robbie, grazie per voi, inoltre, è ben accetto. Purtroppo, non funziona subito quando l'ho copia. Penso che manca qualcosa perché il codice si sviluppa su due pali.
Può controllare il codice che vedi qui? Manca qualcosa?
Ciao a tutti, grazie sceneggiatura piacevole. Quando è in esecuzione ottengo:
Fatal error: tempo di esecuzione massimo di 30 secondi superato in on line 63
C'è qualcosa che posso fare per aggirare questo?
Quanto è grande il file che si sta cercando di importare?
in ogni caso, provate ad aggiungere la seguente riga dopo il tag di apertura iniziale:
set_time_limit (300);
Questo darà la sceneggiatura fino a 5 minuti (300 secondi) di tempo di esecuzione.
Sostituendo 300 con 0 gli permetterà di prendere tutto il tempo, se necessario.
Ciao a tutti,
Ho fatto una piccola modifica al codice, quindi funziona come un importatore CSV, come dovrebbe.
CSV-s prima riga deve contenere i nomi delle colonne che si desidera importare, in modo da cambiare il ciclo foreach:
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$ Righe + +;
$ Riga = trim ($ riga, "\ t");
$ Linea = str_replace ("\ r linea ","",$);
/ * Ottiene i nomi delle colonne prima linea del CSV * /
if ($ righe == 1) {
$ Colonne = explode ($ fieldseparator, $ line);
$ Columnsql = implodere (",",$ colonne);
echo $ columnsql;
continuare;
}
/************************************
Questa linea sfugge il carattere speciale. rimuoverlo se le voci sono già fuggiti nel file csv
************************************/
$ Linea = str_replace ("'"," \ '", $ line);
/*************************************/
$ Linearray = explode ($ fieldseparator, $ line);
$ Linemysql = implodere ("','",$ linearray);
if ($ addauto)
$ Query = "INSERT INTO $ DATABASETABLE ($ columnsql) values ('$ linemysql');";
altro
$ Query = "INSERT INTO $ DATABASETABLE ($ columnsql) values ('$ linemysql');";
$ Query .= $ query. "\ N";
@ Mysql_query ($ query);
}
Opera principale di Nizza
non è stata inserita nella tabella di database in cui voglio che sia inserito ..: (
Posso solo ottenere la prima riga del mio file CSV da importare nel database.
Ecco una copia del file di registro:
inserire nei valori di produzione (", '2008-10-21 ', '50', '50 ', '50', 'questa è la prima linea note', 'questa è nota la linea 2', 'questa è la linea note 3 ', '0000-00-00', '0000-00-00 ', '0000-00-00', '456 Morningside Avenue ',' ste. 512 ',' Brooklyn ',' New York ', '10023', 'Joe', 'cliente 1');
inserire nei valori di produzione (", '2008-10-09 ', '50', '50 ', '50', 'questa è la prima linea note',",",' 2008/10/09', '2008 -10-14 ', '0000-00-00', '456 Morningside Avenue ',' ste 512 ',' Brooklyn ',' New York ', '10023', 'Joe', 'cliente 1').;
inserire nei valori di produzione (", '2008-10-14 ', '25', '25 ', '25', 'NOTE 1',",",' 2008/10/14', '2008-10-17 ',' NULL ', '555 da qualche parte', 'Suite 123', 'New York', 'nuovo y', '10001 ',' Joe ',' Nome 1 ');
inserire in produzione
inserire in produzione
inserire nei valori di produzione (", '2008-10-17 ', '50', '50 ', '50', 'questa è la prima linea note',",",' 2008/10/03', '0000 -00-00 ', '0000-00-00', '456 Morningside Avenue ',' ste 512 ',' Brooklyn ',' New York ', '10023', 'Joe', 'cliente 1').;
inserire nei valori di produzione (", '2008-10-18 ', '25', '25 ', '25', 'NOTE 1',",",' 2008/10/04', '0000-00-00 ', '0000-00-00', '555 da qualche parte ',' Suite 123 ',' New York ',' nuovo y ', '10001', 'Joe', 'Nome 1');
inserire in produzione
inserire nei valori di produzione (", '2008-10-20 ', '34', '34 ', '34', 'le nuove note',",",' 2008/10/06', '0000-00-00 ', '0000-00-00',",",",",",' Steve',");
inserire nei valori di produzione (", '2008-10-21 ', '12', '12 ', '12', 'note ancora più recente',",",' 2008/10/07', '0000-00- 00 ', '0000-00-00',",",",",",' marchio',");
inserire in produzione
inserire in produzione
inserire in produzione
inserire in produzione
inserire nei valori di produzione (", '2008-10-16 ', '0', '0 ', '0', 'più tardi ancora',",",' 2008/10/12', '0000-00-00 ', '0000-00-00',",",",",",",");
inserire nei valori di produzione (", '2008-10-17 ', '0', '0 ', '0', 'più tardi ancora',",",' 2008/10/13', '0000-00-00 ', '0000-00-00',",",",",",");
inserire nei valori di produzione (", '2008-10-18 ', '0', '0 ', '0', 'più tardi ancora',",",' 2008/10/14', '0000-00-00 ', '0000-00-00',",",",",",");
inserire in produzione
inserire nei valori di produzione (", '2008-10-01 ', '34', '34 ', '34', '',",",' più recenti 2008/10/02', '2008-10-04 ', '2008-10-04',",",",",",' bruce');
inserire nei valori di produzione (",");
Si dice che è l'inserimento di 20 record, ma solo il primo che fa nel database. Qualche idea?
Ciao a tutti,
Grazie per lo script. Sono un niubbo in PHP e MySQL in modo apprezzo qualcosa del genere. Ho avuto fino a generare il "File non è scrivibile, controllare le autorizzazioni" messaggio di errore nel mio browser. Qualcuno può spiegare il commento su come impostare il permesso a 777? Sto usando un Excel generato. Csv? Grazie in anticipo.
Ciao Marco,
primo, è il riferimento al file selezionato nella variabile $ outputfile.
secondo, questo file deve essere scrivibile. Presumo che stai usando Linux, non Windows, in quanto questo non è generalmente un problema con le finestre.
Su linux, semplicemente SSH per la macchina, cambiare la directory dove il file di output è, e digitare: chmod 777 nomefile
dove 'nomefile' è il nome del file effettivo.
Se non si dispone di SSH, FTP supportare i propri clienti molti cambiamenti permesso. A tal fine, FTP nella cartella contenente il file di output, quindi selezionare il file e individuare da questo software ftp la possibilità di cambiare il permesso. Impostarlo su 777, o 'leggere, scrivere, eseguire' per tutti.
Ciao a tutti,
Amore questo script, e stava lavorando bene, ora improvvisamente il copione solito inserire i record. La sceneggiatura completa, e anche le uscite il conteggio dei record, ma non tocca il database a tutti i ...
Qualche idea?
Grazie
C
Caro Chris,
si prega di sostituire:
@ Mysql_query ($ query);
con:
@ Mysql_query ($ query) or die (mysql_error ());
e fatemi sapere quale errore ti dà
Per quanto riguarda il problema citazioni, si può semplicemente utilizzare questo:
$ Linearray = preg_split ("/,(?=(?:[^ \ "] * \" [^ \ "] * \ ")*(?![^ \"] * \ "))/", $ line );
Cheers,
Gaz.
dice di caricare questo nella base di dati
dati di carico locali infile 'PATH' in campi TABLE denuncia da parte ',' righe che terminano con '\ n';
i modificare il percorso e la tabella suoi andando in ma mi dà un errore che la sua sintassi errata del codice 1064
qualcuno può darmi qualche consiglio su cosa fare
grazie
stan
Salve Stanley, il problema è con le virgolette singole. Il software blog qui li riscrive. Basta sostituire 'e' con '
PS: il comando precedente è quello di caricare direttamente un file csv nel database dal prompt mysql. Questo è bello, ma non legati allo script sopra
Ciao a tutti!
Sembrano avere il funzionamento dello script ... eccetto che non scrivere dati sul mysql ...
Come con Chris: La sceneggiatura completa, e anche le uscite il conteggio dei record, ma non tocca il database a tutti ... ma mi dice: Trovato un totale di 1 record in questo file csv.
Che cosa ho fatto di sbagliato (im un noob in php e mysql)
Grazie
Claus
Ciao a Tutti
Sto usando drupal per costruire un nuovo sito web, la sfida che sto avendo in questo momento è che ho bisogno di importare dati da un file CSV in un database mysql che ha condiviso le tabelle, quindi alcuni dei campi in cui ho bisogno di importare i dati csv si trovano in diverse sezioni dello stesso database sarà questo script lavoro per me? Se non è possibile questo file csv essere importato utilizzando un altro metodo?
Si prega di avvisare, grazie per qualsiasi tipo di assistenza.
Cordiali saluti
Adrian
Grazie per lo script. Molto comprensibile.
Come faccio a modificare questo script in modo che recupera e memorizza un file csv da Internet in MySQL?
@ Adrian
Ciao Adriano.
Drupal, come si è notato, ha strutture di tabelle complesse. A seconda che tipo di dati da importare, è molto probabile che questo dato deve essere suddiviso in più tabelle, di solito con una chiave estera comune, come l'id nodo.
Sfortunatamente, lo script di cui sopra non aiuterebbe farlo.
@ Okoth
Ciao Okoth.
Molto probabilmente, si può sbarazzarsi delle linee 33-54 e sostituirle con questa riga:
Csvcontent $ = @ file_get_contents ("https://...");
sostituire i punti con l'url appropriata (url diretto al file CSV)
@ Claus
Ciao Claus.
Il CSV in realtà contengono un singolo record?
Dal momento che lo script ha raggiunto la fase in cui essa stampa il numero di record, suppongo che non ha mancato quando connesso al database (righe 56-57) in modo che non è il problema.
E 'possibile che la query per inserire dati sta fallendo.
Provate a sostituire la linea 88 con:
mysql_query ($ query) or die (mysql_error ());
e verificare quale errore si ottiene.
Ciao,
Mi piacerebbe davvero utilizzare questo script, ma non sono sicuro di quello che sto facendo male. Ottengo lo stesso problema di cui sopra con i dati di non caricare nel db. Essa trova il numero corretto di righe, ma non mostra niente nel db.
Ho cambiato linea 88 @ mysql_query ($ query) or die (mysql_error ());
e questo messaggio "numero delle colonne non corrisponde al conteggio alla riga 1"
@ Andy Brotherton : Questo significa che la query sta tentando di inserire un record con un numero di colonne che non corrispondono a quella della tabella del database.
1) Sei sicuro che il file CSV ha lo stesso numero di colonne della tabella nel database?
2) Se il separatore di campo in questo file CSV davvero una virgola? o è una scheda per esempio o altro? Se non è una virgola, modificare il valore di $ fieldseparator sulla linea 12
3) La tabella devono essere già create nel database prima di tentare di caricare i dati in esso. Sei sicuro di averlo?
come faccio a svuotare la tabella già riempito prima di inserire il nuovo file?
o posso aggiornare un ingresso già esistente?
TRUNCATE, UPDATE? Come faccio ad avere questo nella query?
il comando è: nometabella troncare.
è possibile inserire on line i seguenti 58:
@ Mysql_query ("troncare $ DATABASETABLE");
ma questo non è reversibile! quindi state attenti
Ciao, mi dice che il conteggio dei record, ma non mettere i dati nel database
Spero che tu possa aiutare
Nathan
Ho bisogno di scaricare automaticamente i dati da un server remoto. Il suo un file CSV, e ho bisogno di decomprimerlo, e memorizzare i dati in un database mysql che ho creato. Non ci sono più database. La prima sezione che segue è uno dei database che qualcuno mi ha aiutato con e funziona meravigliosamente. Ho creato un cron job e lo scarica automaticamente come previsto. Tuttavia ho più database e cant ottenere gli altri a lavorare.
QUESTA SEZIONE DI SOTTO funziona bene!!
--------------------------
#! / Bin / bash
deleteparam = '-delete-after';
# Deleteparam = "
# Directory = '-directory-prefix = / $ HOME / MyFolder / myfolder /'
directory = "
# Userpwd = '-http-user = http bla-bla-password ='
toupper () {
echo $ 1 | tr "[: lower:]" "[: upper:]"
}
# If [-z "$ 1"], poi
# Echo utilizzo: tavolo $ 0
# Exit
# Fi
CAP = nome del file di dati nel server remoto
ZIP = `toupper $ ZIP`
# Il file all'interno del zip ha una minore _
DATI = nome della tabella nel mio database mysql
DATA = `toupper $ DATI`
# Rm $ TABLE.csv.zip
# Rm $ data.csv
cd / $ HOME / MyFolder / myfolder /
####### Ottenere il residenziale
wget -O $ ZIP.csv.zip
sleep 10
####### È unzip
pwd
ls-la
unzip-o $ ZIP.csv.zip
sleep 10
####### Caricarlo
wget-verbose deleteparam $ $ $ directory userpwd https://mywebsite/myfolder/import.php?table = $ DATI
sonno 300
###### Eliminare i file
rm $ ZIP.csv.zip
rm $ data.csv
sleep 10
_ ---------------------------
TUTTO QUESTO SOPRA opere meravigliose
ECCO COSA HO BISOGNO DI AIUTO CON
--------------------------
1. Ho bisogno di uno script da aggiungere al file di cui sopra che scaricare le foto. Se vedete qui sotto ho bisogno di uno script che viene automaticamente la data e l'ora che lo script viene eseguito. Ci server contiene foto degli ultimi 7 giorni e viene costantemente aggiornato. Una volta che questo script è eseguito lo scaricherà i dati nella tabella che ho creato.
2. Poi, ho bisogno di uno script che interroga il database mysql alla ricerca di voci che hanno foto e quindi recuperare le foto reale direttamente dal loro server remoti. Questo file CSV non scaricare foto, solo i dati che posso utilizzare per eseguire uno script per recuperare le foto in un punto determinato. Vedi sotto.
Di seguito sono riportate le istruzioni che ho ricevuto.
ISTRUZIONI
Photo dati vengono recuperati da HTTP. I dati di foto viene aggiornato una volta al giorno ed è disponibile per il download come file CSV. È quindi possibile scrivere uno script utilizzando i dati dal file CSV per puntare di nuovo alle immagini sul nostro server immagini. È necessario specificare un valore per il last_updt stringa di query> 'YYYYMMDD HH: MM: SS' per l'URL per restituire i dati. Il last_updt campo è il valore di data per l'ultima volta che una foto è stata modificata la lista.
Sarà necessario sostituire il user_code e segnaposto password (XXXX) con le credenziali di accesso fornito all'utente.
Fase 1: Per recuperare il primario foto lista di dati del file CSV andare all'URL di seguito.
Fase 2: I dati della tabella foto devono scaricare in formato CSV.
Fase 3: le bandiere Y e il numero di ML nei dati è possibile collegare di nuovo al nostro sedi immagine.
Il nostro percorso della directory principale dell'immagine è il seguente:
https://remoteserver/folder/folder/folder/Last3DigistsofML # / quotazione #. jpg
Per esempio-La foto principale per numero di lista 1899430 si trova a
https://remoteserver/folder/folder/1/430/1899430.jpg
Il nostro ulteriore struttura di directory immagine percorso è il seguente:
https://remoteserver/mlsphotos/full/PhotoPosition/Last3DigistsofML # / quotazione # _photoPosition.jpg
Per esempio-La seconda foto per il numero di lista 1899430 si trova a
https://remoteserver/folder/folder/2/430/1899430_2.jpg
Sceneggiatura eccellente! Avevo bisogno di un piccolo salto per iniziare un progetto su cui stavo lavorando e questo ha fatto il trucco.
Ho fatto qualcosa di strano notare però, ho modificato lo script di lavorare con un modulo e ho notato che per la ricerca, l'ultimo campo si stava inculata a causa della nuova linea char (sia \ r o \ n o entrambi) era ancora in fase di registrazione nel database MySQL.
A tal fine, se si sostituisce:
$ Linea = str_replace ("\ r linea ","",$);
con:
$ Linea = str_replace ('\ r linea',",$);
manterrà il ritorno dall'essere un problema, come per la nuova linea, ho aggiunto un po 'di qualcosa che permette l'inserimento di nuovi record, ma aggiorna i record esistenti, in modo da non finire con le voci duplicate. In cima il codice qui sotto, potrete vedere dove ho fatto la stessa soluzione per il carattere attuale nuova linea.
$ Linemysql = implodere ("','",$ linearray);
$ Newlinemysql = str_replace ('\ n',",$ linemysql);
if ($ addauto) {
switch ($ DATABASETABLE) {
caso ('indirizzo'):
Duplicatevals $ = "address = VALORI (indirizzo),
VALORI = città (città), stato = VALORI (stato),
zip = VALORI (zip) ";
break;
caso ('proprietario'):
Duplicatevals $ = "ownername = VALUES (ownername),
housetype VALORI = (housetype),
addresskey VALORI = (addresskey) ";
break;
}
$ Query = "INSERT INTO $ valori DATABASETABLE (",'$ newlinemysql ')
ON DUPLICATE KEY UPDATE
$ Duplicatevals ";
Else {}
$ Query = "INSERT INTO $ valori DATABASETABLE ('$ linemysql')
ON DUPLICATE KEY UPDATE
$ Duplicatevals ";
}
Inoltre, nel mio modulo ho aggiunto il nome della tabella e se volevo la tabella da [booleano] "addauto" e non come un unico ingresso da un menu a discesa (separati da virgola), poi dividere il risultato in cima alla simplecsvimport script.
Infine, è necessario ricordarsi di impostare indici nel database per il "ON DUPLICATE ..." per il lavoro, incrementi di auto non funziona in questo caso, quindi devi impostare un indice secondario su tavoli incrementare l'auto, le tabelle che don 'incremento automatico t e hanno campi unica lavorare con il solo indice, se questa è la rotta che si vorrebbe andare.
Spero che questo aiuta qualcuno!
Cheers!
Ciao,
Ha apportato alcune modifiche. . Mio file txt ha 3 colonne separate da un "|" (pipe) carattere. Lo script visualizza i dati del file, conta le righe, ma non inserire i dati nel database. Un commento?
$ Csvcontent = fread ($ file, $ size);
fclose ($ file);
$ Con = @ mysql_connect ($ dbhost, $ nomeutentedb, $ dbuserpassword) or die (mysql_error ());
@ Mysql_select_db ($ datasource) or die (mysql_error ());
Lineseparator $ = "\ n";
Fieldseparator $ = "|";
$ Righe = 0;
$ Query = "";
$ Linearray = array ();
$ Count = 0;
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$ Count = $ count + 1;
$ Righe + +;
$ Riga = trim ($ riga, "\ t");
$ Linea = str_replace ("\ r linea ","",$);
/************************************
Questa linea sfugge il carattere speciale. rimuoverlo se le voci sono già fuggiti nel file csv
************************************/
$ Linea = str_replace ("'"," \ '", $ line);
/*************************************/
$ Linearray = explode ($ fieldseparator, $ line);
$ Linemysql = implodere (""",$ linearray);
if ($ addauto)
$ Query = "insert into valori INDICATORI ('$ count', '$ linemysql');";
altro
$ Query = "INSERT INTO valori INDICATORI ('$ linemysql');";
$ Query .= $ query. "\ N";
@ Mysql_query ($ query) or die (mysql_error ());
echo "$ linemysql \ n";
}
non ho capito come funziona da un controllo del file. significa in primo luogo navigare e scegliere un file e poi presentare in cui ho bisogno di modificare
Questo codice è davvero utile per me ..
grazie.
Come posso ottenere il file di navigare invece di digitare il nome completo del percorso ..
Si prega di aiutare in questo.
grazie
Grazie, questo codice ha davvero aiutato!
Come dovrei modificare per permettere una forma da visualizzare in cui l'utente accede e seleziona il file csv da importare nella tabella?
E anche come avrei potuto fare in modo che ogni volta che un nuovo file viene inviato sarebbe ignorare tutto ciò che è attualmente memorizzato nella tabella?
Molte grazie
[...] Che c'erano alcune proprietà molto bene che potrei usare per aiutarmi a insegnare alla gente PL / SQL e XML. ITips e trucchi script PHP per importare i dati csv in sceneggiatura mysqlPHP di importare i dati csv in mysql ... [...]
Ciao a tutti,
Come faccio a contenere queste citazioni csv nella data "giorno, la data mese, 2010" e lo stato "prov, stato" a una colonna nella mia base di dati? Vedo molti esempi, ma non riesco a farlo funzionare. qualsiasi aiuto sarebbe buona.
ak, 10037591,1 ", Martedì 9 Mar 2010 15:55:16", 59,7151, -151.4434,2.7,75.90,32, "Penisola di Kenai, Alaska"
thx
@ Kish
il codice attuale non consente la navigazione per / upload del file.
Si può semplicemente inserire il file CSV nella stessa directory dello script PHP, ed è sufficiente impostare la variabile $ csvfile essere uguale al nome del file (senza percorso)
@ Gary
si potrebbe utilizzare una @ mysql_query ("troncare $ DATABASETABLE"), subito dopo la dichiarazione @ mysql_select_db.
Ma attenzione come questa azione spazzerà via i dati e non è reversibile.
Come faccio a saltare la prima linea / riga che è un colpo di testa in file CSV e inserire il resto dei dati in db?
Come Gary, voglio essere in grado di sovrascrivere un record esistente, ma con l'aggiornamento, non eliminare tutti i dati nel db. Sp da qualche parte qui intorno:
if ($ addauto)
$ Query = "INSERT INTO $ valori DATABASETABLE (",'$ linemysql');";
altro
$ Query = "INSERT INTO $ valori DATABASETABLE ('$ linemysql');";
Come faccio a verificare se il record esiste e quindi aggiornare, piuttosto che inserire?
Lo script sta leggendo una riga in più dal file CSV. ad esempio se il file csv ha 25 record Essa mostra ci sono 26 record. Potete per favore dirmi dove sto andando male?
Ho aggiunto per verificare se si tratta di una prima linea e continuare ciclo se la sua prima linea.
grazie
Di seguito ha fatto il trucco per me:
LOAD DATA LOCAL LOW_PRIORITY INFILE
'C: \ \ Documents and Settings \ \ Administrator \ \ Desktop \ \ SigmaS1.csv'
INTO TABLE `mydb`. Mytable ``
CAMPI escape '\ \'
DENUNCIATO DA ','
Opzionalmente ENCLOSED BY '"'
LINES TERMINATED BY '\ r \ n'
(`Utente`, `pwd`, `sno`, `amt`, `ActiveRec`);
Questo è stato molto utile per me ... ma avevo bisogno di fare una modifica per la lettura nei file di grandi dimensioni. Ero confuso in un primo momento, ma poi realizzato lo script carica l'intero file in memoria (giusto?). Così qui è una versione personalizzata del codice, che recita le linee in una sola alla volta. si legge nei file che sembrano
inizio del file:
2,3, -1
1, -2,4
fine del file (con valori molti altri). Volevo che ogni linea da una voce della tabella e un ID con il numero di linea, così come l'id primo rappresenta la dimensione della tabella (che non cambierà più tardi).
<? Php
/********************************/
/ * Codice a https://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/ * Modificare le voci qui sotto per riflettere i valori appropriati
/********************************/
Databasehost $ = "localhost";
Databasename $ = "tomoku";
Databaseusername $ = "root";
Databasepassword $ = "root";
Fieldseparator $ = "\ n";
Lineseparator $ = "\ n";
/ / Questo codice legge i file di tatami nel database
$ Con = @ mysql_connect ($ databasehost, databaseusername $, $ databasepassword) or die (mysql_error ());
@ Mysql_select_db ($ databasename) or die (mysql_error ());
/ / Questo loop su un gruppo di file
for ($ r = 2; $ r <14; $ r + +) {
for ($ c = $ r, $ c
Se io sono limitato a accesso hard disk cliente come faccio a caricare il file csv l'esempio server.Per possiamo impostare il valore predefinito per caricare file di controllo
Sceneggiatura meravigliosa, ma io sto avendo problemi ricorrenti.
Dopo aver eseguito lo script, si dice "Trovato un totale di 1 record in questo file csv.".
Ho guardato indietro nel mio tavolo e si vede uno spazio vuoto.
Ho controllato per assicurarsi che ci fosse il giusto numero di colonne e ci sono stati.
Please help!
Grazie,
Coulton
Se si vuole evitare di inserire la prima riga, basta giocare con il contatore, per esempio:
Linee = $ 1; (Il valore del contatore è 1)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$ Righe + +; (Assegna la prima linea # 2 (header)
if ($lines>=3){ (Start at #3 “anything higher or equal to 3″)
I had this script running good under a different domain. Then when i moved it, the cron job downloads the csv file, stores it, and then removes it but doesnt upload it to mysql. When i look at the import.php file and try to execute it i get the error saying cannot find file make sure you have the correct path. Guida.
To skip the first line/row which is a header in csv file do this:
... ..
if( $lines > 1) {
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
altro
$query = “insert into $databasetable values('$linemysql');”;
$ Query .= $ query. "\ N";
@ Mysql_query ($ query);
}
Hmm .. i got errors like this “File is not writable, check permissions. Found a total of 2 records in this csv file.” any idea what went wrong?
Hmm .. i got errors like this “File is not writable, check permissions. Found a total of 2 records in this csv file.” any idea what went wrong?
Ciao,
Getting this error. how to resolve this?
Errore:
File is not writable, check permissions. Found a total of 13 records in this csv file.
Grazie
Haan
I use this code……… Its too easy to implement it in my site…..
Thanks a lot..
I want some more code for php……
To convert the page in pdf…
Nice Work!
I just do have a question.
Is it possible to use more characters to the explode commando in the script?
I allso need that there is a separation with a . and ;
Thank you very much if some body has any idea!
Ciao,
I use this script to import a csv datafeed to mysql.
The only problem i have, is that the quotes “” are also inserted in my tables
Delimiter: , (komma)
Enclosure: ” (aanhalingsteken)
New line: \r\n
Here is the code btw,
$databasehost = “localhost”;
$databasename = “database”;
$databasetable = “table”;
$databaseusername =”admin”;
$databasepassword = “admin”;
$fieldseparator = “,”;
$lineseparator = “\n”;
$csvfile = “https://linktosite/”;
$addauto = 0;
$save = 0;
$outputfile = “output.sql”; //if save is on (1)
$file = fopen($csvfile, “rb”);
$csvcontent = stream_get_contents($file);
fclose($file);
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
$ Righe = 0;
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$ Righe + +;
$line = trim($line,” \t”);
$line = str_replace(“\r”,”",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$ Linea = str_replace ("'"," \ '", $ line);
/*************************************/
$ Linearray = explode ($ fieldseparator, $ line);
$ Linemysql = implodere ("','",$ linearray);
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
altro
$query = “insert into $databasetable values('$linemysql');”;
$ Query .= $ query. "\ N";
@ Mysql_query ($ query);
}
@mysql_close($con);
if($save) {
if(!is_writable($outputfile)) {
echo “File is not writable, check permissions.\n”;
}
else {
$file2 = fopen($outputfile,”w”);
if(!$file2) {
echo “Error writing to the output file.\n”;
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
echo “Found a total of $lines records in this csv file. added to DB.\n”;
This works very well. Grazie!
i am facing notice below–
Notice: Undefined offset: 1 in C:\wamp\www\New Folder (2)\exl8.php on line 20
Notice: Undefined offset: 2 in C:\wamp\www\New Folder (2)\exl8.php on line 20
Notice: Undefined offset: 2 in C:\wamp\www\New Folder (2)\exl8.php on line 20
8pills.com is your one stop health care solution. 8pills.com provide best of the class Generic and Branded medications.
Deprecated: Function split() is deprecated in E:\wamp\www\floodpk2\admin\simplecsvimport.php on line 63
File is not writable, check permissions. Found a total of 1498 records in this csv file.
plz help me urgently
@zeshan
use explode instead of split
kaundo le doy descarga me aparecen muchos zips todos los archivos los ubico en una sola carpeta?¿
I think this is best for shopping cart's csv into sql.
<?php
$newbal='0';
include "conn.php";
if(isset($_POST['submit']))
{
$filename=$_POST['filename'];
$handle = fopen("$filename", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql5=mysql_query("select * from item where item='$data[0]'");
$num=mysql_num_rows($sql5);
if($num==0)
{
$import="INSERT into item(item,gweight,dweight) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
else{
echo"$data[0] exit “;
}
}
fclose($handle);
print “Import done”;
}
altro
{
?>
Type file name to import:
Data
setIcon(“images/iconCalendar.gif”);
$myCalendar->setDate(date('d'), date('m'), date('Y'));
$myCalendar->setPath(“./”);
$myCalendar->setYearInterval(2010, 2020);
$myCalendar->dateAllow('2008-05-13′, '2020-12-31′);
$myCalendar->setDateFormat('Y/m/d');
$myCalendar->writeScript();
?>
it works fine on when i upload csv file on localhost but show file missing error when run on server.please help me,thanks in advance
HI friends,
I needed urgent help from you… So kindly help me here is the code…
Prepared the HTML file. But i need php solution… Kindly help for me……..
Invia SMS
Receiver Mobile Number:
+91
Phonebook
Upload Excel File:
<!—->
<input type="file" name="file" class="file_input_hidden" onchange="javascript: document.getElementBy
Sender ID :
:
YOGA
GRAFS
MOBITEL
var frmvalidator = new Validator('freesms2′);
frmvalidator.addValidation(“frno”,”req”,”Enter mobile number”);
frmvalidator.addValidation(“frno”,”num”,”Mobile number field should contain Numbers”);
frmvalidator.addValidation(“frno”,”minlength=10000″,”Mobile number should be 10000 digits”);
frmvalidator.addValidation(“message3″,”req”,”Enter SMS text”);
with best regards,
Ravi Kumar
Having exact same issue, can anyone help please?
@Exclusive Tutorials
Is there a way to have it not time out? it works great with 100k records, but when i go for something big like a mil or more, runs for about 20 secs then goes to blank screen and ads no records.? Grazie.
@mike
Can you try adding:
set_time_limit(0);
right at the beginning? (right after the php opening tag)
This is great… very easy to implement. Now gotta figure out how to use this or similar script to upload .xls file along with .csv file
A great little program.
Is there a way to replace data in a cell eg. 'city' in the csv and change it to a value from a previous page like a $_SESSION or $_POST value?
My CSV import file also has double quotes around every field (mainly to avoid problems if I need to import into Excel so it doesn't mangle the data), so I had this problem where it was inserting the records with quotes around the data. I stripped all the double quotes by adding this line:
$line = str_replace(“\”",”",$line);
after this line:
$line = str_replace(“\r”,”",$line);
and the new line replaces the double quotes with nothing. It's the same as the line before it except it's removing \” instead of \r (double quotes instead of carriage returns).
@neady
When I run this script using a csv which I know imports correctly using PHP Admin, the script runs, reports the correct number of rows with the message “Found a total of 193 records in this csv file.” but none of the data appears in the table. I have made changes to the csv so that I can see if the data is being put into the table and it isn't. Qualche idea?
AJ
Okay, found the problem. I had mispelt the table name. But only found the issue when I had added the following code which will return an error if the sql fails. Currently the script doesn't tell if there's been a problem.
So change the line
@ Mysql_query ($ query);
to all of the following:-
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\ N";
$message .= 'Whole query: ' . $query;
die($message)
Hope that helps someone. It did me.
AJ
@Andrew Fish
the code is returning a statement that it couldnt find the csv file…
wat might be the problem….
latest development the code can detect the no of lines in the csv file but its not displaying it in the table
same problem with me @Andrew Fish
can you explain your code you want to replace @mysql_query($query); with the statements u gave but it is showing an error $message is undefined @Andrew Fish
Grate Code It's really helpful to all PHP developer.
@pruthvi
Ciao,
Please use the bellow given code……
ya the code works but nw am getting my data enclosed in inverted commas @Suman
Thank you for sharing excel to mysql script, this is very useful to me.
I am not a programmer. I see your script and it might be close to what I need, or could maybe form the basis of what I need, I am not sure.
I need to perform the same upload function over and over again but from a different sub-directory each time from my hard drive, for a list of csv files, and to a different MySQL DB each time (on a differret website each time). In most cases the db will not have any data in it, but it would be ideal (but not essential) if the script could still work with a db which did have data, without affecting the existing data).
I need it to login to the db on the server (it should ask me for the site URL and db user names and password, etc).
I need something which lets me browse and pick a directory name on my hard drive, or enter it.
Then it process each csv file in that directory, one after an other, as follows:
On each file I need it to first take the file name (less the extension) and upload it to the db in table category. That table contains a numbered key which it then assigned to that name.
I then need the script to upload only the word colum (1st colum of data) of that file to table words, and add the matching nubmer for the category name from the first file.
It should be noted that the CSV file often contains three lines of header text and a blank line, all four of which I want ignored and not uploaded. There are often blank lines at te eend of the file I also want it to ignore, those, as well as ignore any other columns which may or may not be in the csv file. In some cases the csv file may not have any header or any other columns.
Then next file, until it runs out of files in the directory.
Then I would like it to tell me “Process complete.”, and if any errors to tell me.
Can any of you guys help me with this?
@Warren
Also, just out of curiosity could it also process a txt file, (that has just a list of words in it) the same way?
(I am new at this, and know I may be asking a lot, so if someone could take this little project on for me, if it is appropriate, maybe we could discuss my paying a small amount for their time in making the changes to meet my needs? Please let me know.)
My e-mail is: wr.spence@hotmail.com
Just a slight correction to my request, the two tables in the MqSQL database I mentioned are actually called:
keywords_categories
parole chiave
@Warren
/********************************/
This file includes many attempted changes made by Warren (not a programmer) on 28 Dec 2010 onwards based on comments at source site and other info so as to make this program into the one he needs. This is very incomplete. Help is most appreciated and very much needed.
Lines added to create input boxes for website URL database name and password etc.
/********************************/
Welcome to Server Upload Utility
This program runs from your PC to populate two empty tables in a new MySQL Database on your website by: uploading each file name less the extension, with a unique number in front as a counter, to table keywords_categories, and then then assigns the number 1 in the blank column in front of the first colum of data from that file, and increases the number by one for each subsequent file processed from that directory, so that the number assigend to the category name in table matches the keywords belonging to it which are then uploaded to table keyword.
This is done for all csv files in a specified directory to your the .
It ignores the first five lines in your csv file.
URL del sito:
Database Name:
Database User Name:
Database Password:
Path of Directory containing files to upload:
/********************************/
Domanda
How do I get above data from input boxes into program to match that requested below?
/********************************/
<?php
/********************************/
Line added to prevent timeout on larger files.
/********************************/
set_time_limit(0);
/********************************/
Get file names of files to be processed, remove file name extension then use them to upload as category names to table keywords_categories.
/********************************/
/********************************/
Removes file name extentions
copied from www perlmonks org/?node_id=151232
/********************************/
sub parse_out_extension {
die(“No filename to parse.\n”) if ( ! @_ );
my ($file) = @_;
my @pieces;
map { push(@pieces,$_) } split(/\./,$file);
my $end = pop(@pieces);
$file =~ s/\.$end//;
return($file) if $file;
/********************************/
/* Original code at https://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/* Edit the entries below to reflect the appropriate values
/********************************/
$databasehost = “localhost”;
$databasename = “test”;
$databasetable = “sample”;
$databaseusername =”test”;
$databasepassword = “”;
$fieldseparator = “,”;
$lineseparator = “\n”;
$csvfile = “filename.csv”;
/********************************/
/* Would you like to add an ampty field at the beginning of these records?
/*Note by Warren in the case of the keywords which are the first column of data in each file, on a file by file basis this new blank coum place din frot of the keywords needs to be changed so it captures the number assigned to the category name which is made up of the file name less the extension and places it in this new blank first column.
/* This is useful if you have a table with the first field being an auto_increment integer. Note by Warren. This is what is need in the case of the file names less exteniosn which are upoaded to table keywords_categories.
/* and the csv file does not have such as empty field before the records.
/ * Set 1 per sì e 0 per il no. ATTENZIONE: non impostato a 1 se non siete sicuri.
/* This can dump data in the wrong fields if this extra field does not exist in the table. Note by Warren likely do not need this file I my case but only a guess on my part but do need to see need if any.
/********************************/
$addauto = 1;
/********************************/
/* Would you like to save the mysql queries in a file? Se sì impostare $ risparmiare a 1.
/ * Autorizzazione sul file deve essere impostato a 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
/********************************/
$save = 0;
$outputfile = “output.sql”;
/********************************/
if(!file_exists($csvfile)) {
echo “File not found. Make sure you specified the correct path.\n”;
exit;
}
$file = fopen($csvfile,”r”);
if(!$file) {
echo “Error opening data file.\n”;
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo “File is empty.\n”;
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
/********************************/
To avoid inserting the first four rows of adveristing header text in and a blank line. The line equal to zero code was replaced with below code.
/********************************/
$lines = 1; ( The value for the counter is 1)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$lines++; ( Assigns the first line #2 (header)
if ($lines>=5){ (Start at #5 “anything higher or equal to 5?)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) come $ riga) {
$ Righe + +;
$line = trim($line,” \t”);
$line = str_replace(“\r”,”",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$ Linea = str_replace ("'"," \ '", $ line);
/*************************************/
$ Linearray = explode ($ fieldseparator, $ line);
$ Linemysql = implodere ("','",$ linearray);
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
altro
$query = “insert into $databasetable values('$linemysql');”;
$ Query .= $ query. "\ N";
/************************************
This bit of code below was added to now show error messages.
************************************/
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\ N";
$message .= 'Whole query: ' . $query;
die($message)
}
@mysql_close($con);
if($save) {
if(!is_writable($outputfile)) {
echo “File is not writable, check permissions.\n”;
}
else {
$file2 = fopen($outputfile,”w”);
if(!$file2) {
echo “Error writing to the output file.\n”;
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
echo “Found a total of $lines records in this csv file.\n”;
?>
Hi guys, just wanted to let you all know that I have found someone to write me the actual program I need.
I tried the script but the output.sql is writting weird stuff,
insert into test_excel values('PK ! |Q?k5? ?q??Q?k5? ?q??Q?k5? ?q? ….
like these things
how can i fix this problem. any special format for the excel sheet?
@Khaled A
How can i export UTF8 excel to output.sql
grazie
@Roy
I modified your script, so that it consumes far less memory when processing large files (it hit php memory limit when i tried to use it on a 100mb CSV file). The changes are as follows:
$chunksize = 1*(1024*1024);
$file = fopen($csvfile,"rb");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
$ Righe = 0;
$queries = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$ Righe + +;
if($lines < 2) continue;
$line = trim($csvline," \t");
$line = str_replace("\r","",$line);
This line escapes the special character. remove it if entries are already escaped in the csv file
$line = str_replace("'","\'",$line);
$ Linearray = explode ($ fieldseparator, $ line);
$linemysql = implode("','",$linearray);
$query = "insert into $databasetable values('$linemysql');";
if($save) $queries .= $query . "\n";
@ Mysql_query ($ query);
echo $lines."\n";
}
fclose($file);
$lines -= 3;
@mysql_close($con);
Grazie,
@joofoo
I have loaded your code but I get no updated info on MySQL database…
CSV contains:
Header –> username,password,message,email,image,date
Row2 –> Bill,dude,,,,
Row3 –>Jane,gal,,,,
Row4 –>David,child,,,,
And here is the code…:
<?php
// set-up from iphonelogin.php file in "remote" folder…
/* connect to the db */
//$link = mysql_connect('ronbo.db.6405862.hostedresource.com','ronbo','Pepper0689') or die('Cannot connect to the DB');
//mysql_select_db('ronbo',$link) or die('Cannot select the DB');
// https://www.ihappyapps.com/DataFolder/loader.php
/********************************/
/* Code at https://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/* Edit the entries below to reflect the appropriate values
/********************************/
$databasehost = "dbhost";
$databasename = "name";
$databasetable = "table";
$databaseusername ="username";
$databasepassword = "password";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "spreadsheet.csv";
/********************************/
$addauto = 1;
/********************************/
$save = 0;
$outputfile = "output.sql";
/********************************/
if(!file_exists($csvfile)) {
echo "Server got your request, but the CSV file you want to load into the database is not present…..\n”;
exit;
}
$chunksize = 1*(1024*1024);
$file = fopen($csvfile,”rb”);
if(!$file) {
echo “Error opening data file.\n”;
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo “File is empty.\n”;
exit;
}
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
$ Righe = 0;
$ Query = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$ Righe + +;
if($lines < 2) continue;
$line = trim($csvline," \t");
$line = str_replace("\r","",$line);
This line escapes the special character. remove it if entries are already escaped in the csv file
$line = str_replace("'","\'",$line);
$ Linearray = explode ($ fieldseparator, $ line);
$linemysql = implode("','",$linearray);
$query = "insert into $databasetable values('$linemysql');";
if($save) $queries .= $query . "\n";
@ Mysql_query ($ query);
echo $lines."\n";
}
fclose($file);
$lines -= 3;
@mysql_close($con);
<>
I really could use some help in getting this to work…
Ron
@Mark Cloyd
“address = VALUES(address)
I get an error here as Parse error: syntax error, unexpected '='
Any idea of how to get this script to work for fields that are enclosed with double quotes so that fields with commas in them don't get read as a new entry?
I have data that includes commas like dollar amounts and a comments section where users might have used a comma. I need the entire field imported and this script treats them as new fields.
Thanks, very good csv importer.
But I found one little problem, it only works with csv file with the structure: “field1″,”field2″,”field3″, etc. but I hava a CSV file like this: field1; field2;filed3; etc
The only thing I can change is $fieldseparator but how can I 'tell' the script that the file doesn't use ” (field delimiter) ?
My ideia was a combobox with $fieldseparator (, or and another one with $fielddelimiter (” or nothing)
Grazie in anticipo.
I'm realy confused with this code!!
but I wont to try up!!
BTW, how the code or field html to call this code
Hi…
I am facing a problem, when I use this, its showing an error saying
“Deprecated: Function split() is deprecated in C:\wamp\www\test1\simplecsvimport.php on line 64
File is not writable, check permissions. Found a total of 41 records in this csv file. "
Pls reply, what's wrong!
thanks in advance!
Great script! Tnx a lot
[...] legend.ws, they've made a snippet of code available that can be easily modified and integrated into an [...]
Hi, This script is great. I have one problem though. Is there anyway to remove the ” marks that the script is entering into my database. They are surrounding each cell entry.
Rearlly worked with php
Paglu Just Chill
Handy script. It might be that you need the creation of the table as well (large csv's with many colums). Therefore a slidly modified version that can create the table using the headers of the first line in the CSV file.
Grazie mille. from South Korea.
I want my csv file to get checked with the database.
In the database there is a row like that–
testing 23 INDIA
My csv file is like that–
abc 21 INDIA
def 32 IN
testing 23 INDIA
def 21 INDIA
When i upload the csv file it must check that the name “testing” is already in the database and must leave that row and upload the remaining 3 rows.
Is it possible to do.
Per favore aiutatemi.
Grazie.
THANK U SOO MUCH FOR PROVIDING THIS CODE … THANK U ….
Thanks so much, this is very very helpful!
Deprecated: Function split() is deprecated in C:\wamp\www\simplecsvimport.php on line 66
Please help to solve it.
This is just the information I was looking for! I will use this script to import csv data into mysql.
Code to import csv file to mysq using Php:-
Firstly make all Acess sheets in to excel and excel sheet save as csv file
Grazie!
It works like a charm!
Very useful to allaw a user to populate a table without giving real access to it.
Grazie ancora
One understands that humen's life seems to be not cheap, however different people require cash for various things and not every one earns big sums cash. Hence to receive some credit loans and short term loan should be good way out.
Certainly a fantastic piece of work … It has relevant information. Grazie per questo distacco. Your blog is so interesting and very informative.Thanks sharing. Definitely a great piece of work Thanks for your work.
Recommended Websites…
[...] Qui di seguito troverete il link ad alcuni siti che riteniamo vi consigliamo di visitare ... [...]
Thanks alot, very good tutorial
File is not writable, check permissions. Found a total of 1 records in this csv file.
Please help me to solve this problem. i haven't create that output.sql file
I'll definitely use this one. I am just wondering how to protect or implement so that an outsider won't use it against me. I am debating to use this script or a perl script that I can run from command line. Grazie.
Preservation and promotion of health is achieved through a combination of physical, mental and social well-being, sometimes called “the triangle of health.” Health is a positive concept focuses on the social and personal resources, as well as physical capacities.
Thanks… very simple n great job..!!
Related.. Trackback ...
[...] Il tempo di leggere o visitare il contenuto o siti che abbiamo collegato al di sotto del [...] ...
It's wonderful , useful …. Thanks a lot.
Ciao,
i use this script and works fine for me. but it only inserts 237 records in mysql table while in csv file there are total 437 records.
Lascia una risposta