PHP script-import ng data ng csv sa MySQL
Ito ay isang simpleng script na magpapahintulot mong i-import ang data csv sa iyong database. Ito pagdating madaling gamitin dahil maaari mo lamang i-edit ang mga naaangkop na patlang, i-upload ito kasama ang csv file at tawagan ang mga ito mula sa web at ito ay gawin ang natitira.
Pinapayagan ka nitong tukuyin ang delimiter sa csv file na ito, kung ito ay isang kawalang-malay, isang tab atbp din ito nagpapahintulot sa iyo na pinili ang line separator, nagpapahintulot sa iyo upang i-save ang output sa isang file (na kilala bilang isang data SQL dump).
Ito rin permit mong isama ang isang walang laman na patlang sa simula ng bawat hilera, na kung saan ay karaniwang isang integer sa pagdagdag ng auto pangunahing key.
Ang script na ito ay kapaki-pakinabang pangunahing kung wala kang phpmyadmin, o hindi mo nais ang gulo ng log in at gusto ng ilang mga solusyon pag-click, o mo lang ng isang command prompt na tao.
Lang gumawa bang table ay nilikha bago sinusubukang i-dump ang data.
Mabait-post ang iyong mga komento kung kayo kayong mga ulat ng bug.

Very kapaki-pakinabang, salamat sa iyo.
Karaniwan ang gamit ko phpmyadmin, ngunit totoo, sa kaso sa isa ay hindi ito install, at hindi shell access (tulad ng karamihan ng ibinahagi hosting provider), ito ay maaaring dumating sa napaka-madaling gamitin.
Salamat ng maraming ito save ng maraming panahon! Nice script.
[...] Well, ngayon gusto kong ipakita sa iyo ng ibang paraan ng pagkuha ng iyong mga csv file sa SQL, gamit ang PHP code. Para sa piraso ng code, ang buong credit napupunta sa alamat. Kailangan mong tiyakin na ang database ay ginawa bago ka dump ang petsa. /************************************************* *******************************************/ / * Code sa http: / / legend.ws / blog / tip-trick / csv-php-MySQL-import / / * I-edit ang mga entry sa ibaba upang ipakita ang mga naaangkop na halaga /****************** ************************************************** ************************/ $ databasehost = "localhost"; $ databasename = "test"; $ databasetable = "sample"; $ databaseusername = " test "; $ databasepassword ang =" "; $ fieldseparator =", "; $ lineseparator =" n "; $ csvfile =" bbqrest.csv "; /***************** ************************************************** *************************/ / * Gusto mo bang magdagdag ng isang patlang ng ampty sa simula ng mga talaan? / * Ito ay kapaki-pakinabang kung mayroon kang isang table sa unang field ang pagiging isang auto_increment integer / * at ang csv file ay hindi tulad ng walang laman ang patlang bago ang mga talaang. / * Itakda ang 1 para sa yes at 0 para sa walang. Pansin: hindi nakatakda sa 1 kung hindi ka sigurado. / * Ito ay maaaring dump ng mga data sa maling na mga patlang kung ang karagdagang patlang na ito ay hindi umiiral sa table /***************************** ************************************************** *************/ $ addauto = 0; /****************************** ************************************************** ************/ / * Gusto mo bang i-save ang ng mga query ng MySQL sa isang file? Kung oo set $-save sa 1. / * Pahintulot sa file ay dapat nakatakda sa 777. Alinman sa mag-upload ng isang sample file sa pamamagitan ng ftp at / * baguhin ang mga pahintulot, o execute sa prompt: ugnayan output.sql & & chmod 777 output.sql /******************* ************************************************** ***********************/ $ save = 1; $ outputfile = "output.sql"; /*********** ************************************************** *******************************/ [...]
Hi doon, isang maliit na pagbabago para sa mga auto incrementing mga halaga sa haligi 1 (id patlang)
tingnan ang variable $ count.
Ola, Enrico.
/ / $ Salungat = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) o mamatay (mysql_error ());
/ / @ Mysql_select_db ($ databasename) o mamatay (mysql_error ());
$ Linya = 0;
$ Query = "";
$ Linearray = array ();
$ Count = 0;
foreach (split ($ lineseparator, $ csvcontent) bilang $ linya) {
$ Count = $ count + 1;
$ Linya + +;
$ Linya = trim ($ linya, "\ t");
$ Linya = str_replace ("'"," \ '", $ linya);
$ Linearray = sumabog ($ fieldseparator, $ linya);
$ Linemysql = pumutok sa loob ("','",$ linearray);
$ Query = "ipasok sa` iyong db table `halaga ('$ count', '$ linemysql');";
$ Query .= $ query. "\ N";
@ Mysql_query ($ query);
}
/ / @ Mysql_close ($ salungat);
[...] Sa isang katulad na tandaan, dito ay isang pre-ginawa script na ang may-akda nito sabi ni import ng CSV file sa MySQL: PHP script-import ng data ng csv sa MySQL. [...]
[...] /******************************************** ************************************************/ / * Code sa http://legend.ws/blog/tips-tricks/csv-php-mysql-import/ / * I-edit ang mga entry sa ibaba upang ipakita ang mga naaangkop na halaga /************* ************************************************** *****************************/ $ databasehost = "localhost"; $ databasename = "XXXXX"; $ databasetable = "xxxx" ; $ = "xxxx"; $ databasepassword = "xxxx"; $ fieldseparator = ","; $ lineseparator = "n"; $ csvfile = "xport/2008_BF.csv"; databaseusername /********* ************************************************** *********************************/ / * Gusto mo bang magdagdag ng isang patlang ng ampty sa simula ng mga talaan ? / * Ito ay kapaki-pakinabang kung mayroon kang isang table sa unang field ang pagiging isang auto_increment integer / * at ang csv file ay hindi tulad ng walang laman ang patlang bago ang mga talaang. / * Itakda ang 1 para sa yes at 0 para sa walang. Pansin: hindi nakatakda sa 1 kung hindi ka sigurado. / * Ito ay maaaring dump ng mga data sa maling na mga patlang kung ang karagdagang patlang na ito ay hindi umiiral sa table /***************************** ************************************************** *************/ $ addauto = 0; /****************************** ************************************************** ************/ / * Gusto mo bang i-save ang ng mga query ng MySQL sa isang file? Kung oo set $-save sa 1. / * Pahintulot sa file ay dapat nakatakda sa 777. Alinman sa mag-upload ng isang sample file sa pamamagitan ng ftp at / * baguhin ang mga pahintulot, o execute sa prompt: ugnayan output.sql & & chmod 777 output.sql /******************* ************************************************** ***********************/ $ save = 1; $ outputfile = "output.sql"; /*********** ************************************************** *******************************/ [...]
Wow ay cool na ... ay ideya matapos basahin ang iyong coding ... salamat ng maraming
Kabuuang Newbie - pansiwang aking buhok out sinusubukan i-import ang Excel csv sa phpMyAdmin (sa isang Mac). Gusto pag-ibig malaman eksakto kung saan at ano ang gagawin ko sa script php na ito ...?
Steve,
Gusto mong ilagay ang script na ito sa isang folder na web-mapupuntahan, matapos na baguhin ang mga variable na kailangan upang baguhin. Basahin ang mga puna sa ang script upang malaman kung ano ang kailangan mong tukuyin. Pagkatapos, tumawag sa script sa isang web browser, tulad ng:
http://www.example.com/path-to-script/simplescvimport.php
ito ay maging isang magandang ideya na magdagdag ng maiwasan ang mga header sa loob ng csv mula sa na isinumite sa database. O upang lumikha ng isang script na pulls out ang unang hilera at lumilikha ng isang db na gamit ang mga halagang ito bilang pangalan ng haligi.
Nakakakuha ako ng error na ito Hindi nahanap ang file. Siguraduhin na tinukoy mo ang tamang landas.
Maaari anumang isang mabilis tumugon na may i isang bbqrest.csv csv file sa tamang path (root) ...
Rengaraj,
ang csv file ay dapat na sa parehong lugar bilang ang file ng PHP.
Gayundin, hindi mo talaga gamitin ang parehong csv file name.
bbqrest.csv ay isang halimbawa, palitan ang pangalan ng file na ito sa iyong sarili.
Hindi account para sa mga patlang tulad ng linyang ito:
Fname, Lname, "Company, Inc", Lungsod, Estado, Zip
Company at Inc makakuha ng split sa dalawang iba't ibang mga haligi.
Well, narito ang ayusin sa aking naunang komento:
ipasok ito sa pagitan ng:
$ Linearray = sumabog ($ fieldseparator, $ linya);
... Ipasok ang code snippet sa ibaba ....
$ Linemysql = pumutok sa loob ("','",$ linearray);
Hahanap at magkasama mapigil ang lahat "Bagay-bagay, Maraming Bagay-bagay" bago imploding ito.
$ Isang = "";
$ B = "";
$ Qoutecount = 0;
para sa ($ x = 0; $ x -1) {
$ Qoutecount + +;
kung ($ qoutecount == 1)
$ Isang = $ x, / / store ang unang pagkakataon
elseif ($ qoutecount == 2) {
$ Quotecount = 0;
$ B = $ x, / / tindahan sa ikalawang halimbawa
/ / NA AY IT ... itala ang lahat ng mga elemento mula sa $ sa $ b sa $ isang at huwag pansinin ang mga elemento ng anumang matapos $ sa $ b sa bagong array;
$ Newa = ""; / / pagsisimula ng bagong string.
para sa ($ z = $ a; $ z $ ng isang & & $ y
)
; / / Laktawan dahil ito ay bumaba sa loob ng mga masamang elemento ng array
iba
$ Newarray [$ y] = str_replace ('"',",$ linearray [$ y]);
$ Linearray = array_values ($ newarray), / / i-reset ang susi sa bagong array
$ X + +;
}
}
}
makakuha i sa unang karami ng ito gupitin at pahinga ang code sa aking browser. Alam ko ang php ay gumagana dahil ang natitirang bahagi ng site na gumagana.
Ako mag-upgrade sa php5 ang na mahalaga?
pakong-aspili, kung mayroon kang download ito mas maaga kaysa sa nakaraang linggo, palitan ang '<?' sa tuktok sa '<? php' (alisin ang space)
Robbie, salamat para sa iyo karagdagan, medyo ito ay malugod. Sa kasamaang palad, hindi ito gumana kaagad kapag kopyahin ko ito. Tingin ko ang isang bagay ay nawawala dahil sa ang code ay kumakalat sa loob ng dalawang post.
Puwede mong suriin ang code na tulad ng ipinapakita dito? Isang bagay na nawawala?
Hi doon, gandang script salamat. Kapag nagpapatakbo ito nakukuha ko:
Fatal error: Maximum execution time ng 30 segundo lumampas sa linya 63
Mayroon bang anumang maaari kong gawin upang makakuha ng paligid na ito?
Paano malaki ay ang file na iyong sinusubukang i-import?
sa anumang kaso, subukan ang pagdaragdag ang sumusunod na linya matapos ang unang pagbubukas ng mga tag:
set_time_limit (300);
Na ito ay magbibigay ng script hanggang sa 5 minuto (300 segundo) ng pagpapatupad oras.
Pinalitan 300 sa 0 ay pinapayagan ang mga ito upang kumuha ng mas maraming oras kung kinakailangan.
Hi lahat,
Aking ginawa ng isang menor de edad na pagbabago sa iyong code, kaya ito gumagana bilang isang CSV mang-aangkat, bilang dapat.
CSV-s unang linya ay dapat hold ang mga pangalan ng COLUMN na nais mong i-import, kaya baguhin ang FOREACH loop:
foreach (split ($ lineseparator, $ csvcontent) bilang $ linya) {
$ Linya + +;
$ Linya = trim ($ linya, "\ t");
$ Linya = str_replace ("\ r ","",$ linya);
/ * Makakuha ng mga pangalan ng COLUMN mula sa unang linya ng CSV * /
kung ($ linya == 1) {
$ Haligi = sumabog ($ fieldseparator, $ linya);
$ Columnsql = pumutok sa loob (",",$ mga haligi);
echo $ columnsql;
magpatuloy;
}
/************************************
Ang linyang ito escapes ng mga espesyal na character. alisin ito kung entry ay escaped sa csv file
************************************/
$ Linya = str_replace ("'"," \ '", $ linya);
/*************************************/
$ Linearray = sumabog ($ fieldseparator, $ linya);
$ Linemysql = pumutok sa loob ("','",$ linearray);
kung ($ addauto)
$ Query = "ipasok sa $ databasetable ($ columnsql) na mga halaga ('$ linemysql');";
iba
$ Query = "ipasok sa $ databasetable ($ columnsql) na mga halaga ('$ linemysql');";
$ Query .= $ query. "\ N";
@ Mysql_query ($ query);
}
Nice trabaho chief
hindi ito ipasok sa talahanayan ng database kung saan gusto ko ito ipinasok ..: (
Ko lamang makuha ang unang linya ng aking mga CSV file na na-import papunta sa database.
Narito ang isang kopya ng file ng log:
magpasok sa mga halaga ng produksyon (", '2008-10-21 ', '50', '50 ', '50', 'ito ay ang unang linya tala', ito ay tala line 2 ', ito ay tala line 3 ', '0000-00-00', '0000-00-00 ', '0000-00-00', '456 Morningside Ave, Ste 512 ',' Brooklyn ',' NY ', '10023', 'Joe', 'Customer 1');
magpasok sa mga halaga ng produksyon (", '2008-10-09 ', '50', '50 ', '50', ito ay ang unang linya tala',",",' 2008/10/09 ', '2008 -10-14 ', '0000-00-00', '456 Morningside Ave ',' Ste 512 ',' Brooklyn ',' NY ', '10023', 'Joe', 'Customer 1');
magpasok sa mga halaga ng produksyon (", '2008-10-14 ', '25', '25 ', '25', 'NOTA 1',",",' 2008/10/14', '2008-10-17 ',' null ', '555 lugar', suite 123 ',' new york ',' bagong y ', '10001', 'Joe', 'Pangalan 1');
magpasok sa produksyon
magpasok sa produksyon
magpasok sa mga halaga ng produksyon (", '2008-10-17 ', '50', '50 ', '50', ito ay ang unang linya tala',",",' 2008/10/03 ', '0000 -00-00 ', '0000-00-00', '456 Morningside Ave ',' Ste 512 ',' Brooklyn ',' NY ', '10023', 'Joe', 'Customer 1');
magpasok sa mga halaga ng produksyon (", '2008-10-18 ', '25', '25 ', '25', 'NOTA 1',",",' 2008/10/04', '0000-00-00 ', '0000-00-00', '555 lugar ',' suite 123 ',' new york ',' bagong y ', '10001', 'Joe', 'Pangalan 1');
magpasok sa produksyon
magpasok sa mga halaga ng produksyon (", '2008-10-20 ', '34', '34 ', '34', 'bagong tala',",",' 2008/10/06', '0000-00-00 ', '0000-00-00',",",",",",' Steve',");
magpasok sa mga halaga ng produksyon (", '2008-10-21 ', '12', '12 ', '12', 'kahit na mas bagong mga tala',",",' 2008/10/07', '0000-00- 00 ', '0000-00-00',",",",",",' markahan',");
magpasok sa produksyon
magpasok sa produksyon
magpasok sa produksyon
magpasok sa produksyon
magpasok sa mga halaga ng produksyon (", '2008-10-16 ', '0', '0 ', '0', 'mamaya pa rin',",",' 2008/10/12', '0000-00-00 ', '0000-00-00',",",",",",",");
magpasok sa mga halaga ng produksyon (", '2008-10-17 ', '0', '0 ', '0', 'mamaya pa rin',",",' 2008/10/13', '0000-00-00 ', '0000-00-00',",",",",",");
magpasok sa mga halaga ng produksyon (", '2008-10-18 ', '0', '0 ', '0', 'mamaya pa rin',",",' 2008/10/14', '0000-00-00 ', '0000-00-00',",",",",",");
magpasok sa produksyon
magpasok sa mga halaga ng produksyon (", '2008-10-01 ', '34', '34 ', '34', 'napaka pinakabagong',",",' 2008/10/02', '2008-10-04 ', '2008-10-04',",",",",",' Bruce');
magpasok sa mga halaga ng produksyon (",");
Ito sabi ni ito ay pagpasok ng 20 mga talaan, ngunit lamang ang unang isa ay gumagawa ito sa database. Anumang saloobin?
Hi lahat,
Salamat para sa script. I'ma noob sa PHP at MySQL upang Pinahahalagahan ko talaga ang isang bagay tulad nito. Nakatanggap ako tulad ng pagbuo ng "File ay hindi writable, suriin ang mga pahintulot" error na mensahe sa aking browser. Maaari isang tao mangyaring ipaliwanag ang mga komento tungkol sa setting ng pahintulot sa 777? Ako gamit ang isang Excel-generated. Csv file? Salamat in advance.
Hi Mark,
una, ito ay tumutukoy sa ang file na iyong pinili sa ang $ outputfile variable.
pangalawa, ang file na ito ay pangangailangan upang maging writable. Ipinapalagay ko na ikaw ay gumagamit ng Linux, hindi window, tulad ng ito ay karaniwang hindi isang isyu sa bintana.
Sa Linux, lang SSH ang machine, baguhin sa direktoryo kung saan ang output file, at i-type: chmod 777 filename
kung saan 'filename' ay ang aktwal na pangalan ng file.
Kung wala kang SSH, maraming FTP kliyente support pahintulot na baguhin. Para sa layunin na ito, FTP sa folder na naglalaman ng mga output file, pagkatapos piliin ang file na ito, at hanapin mula sa ftp software ang pagpipilian upang baguhin ang pahintulot. Itakda ito sa 777, o 'basahin, magsulat, mag-execute' para sa lahat.
Uy bawat tao'y,
Love ang script na ito, at ito ay gumagana multa, ngayon ay biglang script sanay ipasok ang mga tala. Script na makumpleto, at kahit outputs ang bilang ng tala, ngunit hindi hawakan ang database sa lahat ...
Anumang mga ideya?
Salamat
C
Minamahal Chris,
mangyaring palitan:
@ Mysql_query ($ query);
sa:
@ Mysql_query ($ query) o mamatay (mysql_error ());
at hayaan mo sa akin kung ano ang error ay nagbibigay sa iyo ng
Sa patungkol sa isyu quote, maaari mo lamang gamitin ang:
$ Linearray = preg_split ("/,(?=(?:[^ \ "] * \" [^ \ "] * \ ")*(?![^ \"] * \ "))/", $ line );
Cheers,
Gaz.
ito sabi ni-load ito sa ang data base
load ang data lokal infile 'Path' sa mga patlang ng TALAAN ng table na tinapos ng ',' linya na tinapos ng '\ n';
baguhin ko ang path at ang table na nito pagpunta sa ngunit nagbibigay ito sa akin ng isang error na ang maling syntax ng code 1064
Maaari sinuman ninyo ako ilang payuhan sa kung ano ang gagawin
salamat
Stan
Hi Stanley, ang problema ay sa solong quotes. Ang blog na software dito rewrites sa kanila. Lang palitan ang 'at' ng '
PS: ang command sa itaas ay na direktang-load ang isang csv file sa database mula sa MySQL prompt. Ito ay gandang ngunit hindi na may kaugnayan sa ang script sa itaas
Hi sa lahat!
Mukhang gumagana ang script ... exept na ito ay hindi isulat ang data sa ang MySQL ...
Tulad ng sa Chris: script makumpleto, at kahit outputs ang bilang ng tala, ngunit hindi hawakan ang database sa lahat ... pero nagsasabi sa akin: Natagpuan ng isang kabuuang 1 talaan sa csv file na ito.
Ano ang gagawin ko mali (im isang noob sa php at MySQL)
Salamat
Claus
Kumusta Lahat
Ako gumagamit ng drupal na bumuo ng isang bagong website, ang hamon na ako nagkakaroon ngayon ay na kailangan ko upang i-import ng mga data mula sa isang CSV file sa isang MySQL database na ay nagbahagi ng mga talahanayan, samakatuwid ang ilan ng mga patlang na kung saan na kailangan kong i-import ng mga data csv sa iba't ibang mga seksyon ng parehong database ay ang script na ito ay gumagana para sa akin? Kung hindi ang csv file na ito mai-import gamit ang ibang paraan?
Mangyaring payuhan, salamat sa iyo para sa anumang tulong.
Regards
Adrian
Salamat para sa script. Very maliwanag.
Paano ko baguhin ang script na ito upang ito fetches at iniimbak ang isang csv file mula sa Internet sa MySQL?
@ Adrian
Hello Adrian.
Drupal, bilang mo nabanggit, ay may kumplikadong kaayusan table. Depende sa kung anong uri ng mga data ay import mo, ito ay malamang na ang data na ito ay nangangailangan na split sa maramihang mga talahanayan, karaniwang may isang pangkaraniwang dayuhan key tulad ng node id.
Kasamaang palad, ang script sa itaas ay hindi makatulong na gawin iyon.
@ Okoth
Hello Okoth.
Malamang, maaari mong tanggalin ng mga linya 33-54 at palitan ang mga ito sa isang linya na ito:
$ Csvcontent = @ file_get_contents ("http://...");
palitan ang mga tuldok na may naaangkop na url (direct url sa ang CSV file)
@ Claus
Hello Claus.
Talaga ba CSV ang naglalaman ng isang solong tala?
Dahil ang script ay naabot ang yugto kung saan ito outputs ang bilang ng mga talaan, ipinapalagay kong hindi ito mabibigo kapag ito ay konektado sa database (linya 56-57) kaya na hindi ang problema.
Ito ay posible na ang query upang ipasok ang mga data ay nanghihina.
Subukan ang pagpapalit ng line 88 sa:
mysql_query ($ query) o mamatay (mysql_error ());
at suriin kung ano ang error na makakuha ka.
Hello,
Gusto ko talagang nais na gamitin ang script na ito ngunit hindi ako sigurado kung ano ako paggawa ng mali. Nakukuha ko ang parehong problema na binanggit sa itaas sa mga data na hindi naglo-load sa ang db. Hahanapin ang tamang bilang ng mga hilera ngunit walang nagpapakita sa db.
Nagbago ko line 88 @ mysql_query ($ query) o mamatay (mysql_error ());
at makakuha ng mensaheng ito "Haligi bilang ay hindi tumutugma ang bilang ng halaga sa hanay 1"
@ Andy Brotherton : ay nangangahulugan na ang query na iyon ay sinusubukan upang magpasok ng isang record sa isang bilang ng mga haligi na hindi tumugma sa ng table ng database.
1) Sigurado ka ba na ang mga CSV file ay ang eksaktong parehong bilang ng mga haligi ng talahanayan sa database?
2) ang patlang ng separator sa CSV file talaga ng kuwit? o ito ng isang tab halimbawa o iba pang? Kung ito ay hindi isang comma, baguhin ang halaga ng $ fieldseparator on line 12
3) Ang talahanayan sa kailangan na nilikha sa database bago sinusubukang i-load ang data sa ito. Sigurado ka ba na mayroon kang?
kung paano i walang laman ang aking napuno na table bago pagpasok ng bagong file?
o maaari i-update ang isang na umiiral input?
Pungusan, UPDATE? Paano ako makakakuha ng ito sa tanong?
ang command ay: pungusan tablename.
maaari mong ipasok ang sumusunod sa linya 58:
@ Mysql_query ("pungusan $ databasetable");
ngunit ito ay hindi baligtaran! kaya maging maingat
Hi, ito ay nagsasabi sa akin ang record bilang ngunit hindi paglalagay ng mga data sa database
Umaasa maaari kang makatulong
Nathan
Kailangan ko upang i-download ang data ng awtomatikong mula sa isang remote server. Nito sa isang CSV file, at i kailangan upang magsiper ito, at mag-imbak ng data sa isang MySQL database na i nilikha. Mayroong maramihang mga database. Ang unang seksyon sa ibaba ay isa ng database na ang isang tao ay nakatulong sa akin at ito gumagana kamangha-mangha. Ako magse-set up ng isang cron trabaho at ito ay awtomatikong-download ito bilang naka-iskedyul na. Gayunpaman i higit pa database at nakahilig sa iba upang gumana.
THIS SECTION sa IBABA Works Fine!!
--------------------------
#! / Bin / malakas na palo
deleteparam = '-tanggalin-pagkatapos;
# Deleteparam = "
# Direktoryo = '-directory-prefix = / $ HOME / myfolder / myfolder /'
direktoryo = "
# Userpwd = '-http-user = blah-http-password = blah'
toUpper () {
echo $ 1 | tr "[: mas mababa:]" "[: itaas:]"
}
# Kung [-z "$ 1"]; pagkatapos
# Echo paggamit: $ 0 table
# Exit
# Fi
ZIP = pangalan ng data file sa remote na server
ZIP = `toUpper $ ZIP`
# Ang file sa loob ng zip ay may isang mas mababa _
DATA = pangalan ng talahanayan sa aking MySQL database
DATA = `toUpper $ DATA`
# Rm $ TABLE.csv.zip
# Rm $ DATA.csv
cd / $ HOME / myfolder / myfolder /
####### Ang tirahan
wget -O $ ZIP.csv.zip
matulog 10
####### Magsiper ito
pwd
ls-la
magsiper-o $ ZIP.csv.zip
matulog 10
#######-Load ito
wget-maligoy $ deleteparam $ direktoryo $ userpwd http://mywebsite/myfolder/import.php?table = $ DATA
matulog 300
###### Tanggalin ang mga file
rm $ ZIP.csv.zip
rm $ DATA.csv
matulog 10
_ ---------------------------
LAHAT NG ITO ITAAS gumagana ang kahanga-hangang
ITO AY ano ang kailangan ko ng tulong sa
--------------------------
1. Kailangan ko ng script upang idagdag sa sa itaas na file na i-download ang mga larawan. Kung nakikita mo sa ibaba kailangan i ng isang script na awtomatikong na nakakakuha ng CURRENT petsa at oras na ang script ay tumakbo. May server hawak ng mga larawan mula sa huling 7 araw at patuloy na-update. Kapag ang script na ito ay tumakbo ito i-download ang mga data sa table na i nilikha.
2. Pagkatapos, Kailangan ko ng script na mga query sa ang MySQL database na naghahanap para sa mga entry na ng mga larawan at pagkatapos makuha ang aktwal na mga larawan nang direkta mula sa kanilang mga remote server. Ang csv file na ito AY HINDI download larawan, lamang ang mga data na maaari kong gamitin upang magpatakbo ng isang script upang makuha ang mga larawan sa isang ibinigay na lugar. Tingnan sa ibaba.
Nasa ibaba ang mga tagubilin Nakatanggap ako ng.
TAGUBILIN
Photo data ay nakuha sa pamamagitan ng HTTP. Ang mga larawan data ay ina-update isang beses araw-araw at ito ay magagamit para sa pag-download bilang isang CSV file. Pagkatapos ay maaari mong magsulat ng isang script na gamit ang mga data mula sa CSV file sa point bumalik sa ang mga imahe sa aming mga imahe server. KAILANGAN MO supply A VALUE PARA SA QUERY last_updt STRING> 'YYYYMMDD HH: MM: SS para sa mga URL upang bumalik ang mga data. Ang field last_updt ay ang halaga ng petsa para sa mga huling oras na ang isang larawan ay binago sa sa listahan.
Kailangan mong palitan ang user_code at password may hawak ng lugar (XXXX) sa mga kredensyal login na ibinigay sa iyo.
Hakbang 1: Upang makuha ang pangunahing listahan ng larawan ng data CSV file pumunta sa URL sa ibaba.
Hakbang 2: Ang data ng table ng mga larawan ay dapat na-download sa isang CSV format.
Hakbang 3: Gamit ang mga flag ng Y at ang ML Bilang sa mga data na maaari mong link pabalik sa aming mga lokasyon ng imahe.
Direktoryo ng aming pangunahing path imahe ay tulad ng sumusunod:
http://remoteserver/folder/folder/folder/Last3DigistsofML # / listahan #. jpg
Halimbawa Ang pangunahing larawan para sa listahan ng numero 1899430 ay matatagpuan sa
http://remoteserver/folder/folder/1/430/1899430.jpg
Aming direktoryo ng karagdagang imahe istraktura path ay tulad ng sumusunod:
http://remoteserver/mlsphotos/full/PhotoPosition/Last3DigistsofML # / listahan # _photoPosition.jpg
Halimbawa-Ang ikalawang larawan para sa listahan ng numero 1899430 ay matatagpuan sa
http://remoteserver/folder/folder/2/430/1899430_2.jpg
Magaling script! Kailangan ko ng isang maliit na tumalon simulan para sa isang proyekto na ako ay nagtatrabaho sa at ito ay ang lansihin.
Ko ang paunawa ng isang bagay na kakaiba gayunpaman, ako binago ang script upang gumana sa isang form at ako ay paunawa na para sa paghahanap, ang huling field ay nakakakuha buggered up dahil ang bagong linya magpasinda (alinman \ r \ n o pareho) ay pa rin na naitala sa ang MySQL database.
Sa layong iyon, kung palitan mo:
$ Linya = str_replace ("\ r ","",$ linya);
sa:
$ Linya = str_replace ('\ r',",$ linya);
ito ay panatilihin ang mga bumalik mula sa pagiging isang problema, para sa bagong linya, ako ay nagdagdag ng isang maliit na isang bagay na nagbibigay-daan para sa pagpasok ng bagong mga talaan, ngunit ang mga update umiiral talaan, kaya na hindi mo end up na may duplicate entry. Sa tuktok ng code sa ibaba, makikita mo kung saan ko ginawa ang parehong ayusin para sa aktwal na bagong linya magpasinda.
$ Linemysql = pumutok sa loob ("','",$ linearray);
$ Newlinemysql = str_replace ('\ n',",$ linemysql);
kung ($ addauto) {
lumipat ($ databasetable) {
kaso ('address'):
$ Duplicatevals = "address = halaga (address),
lungsod = halaga (lungsod), estado = halaga (estado),
zip = halaga (zip) ";
pahinga;
kaso ('may-ari):
$ Duplicatevals = "ownername = halaga (ownername),
housetype = halaga (housetype),
halaga ng addresskey = (addresskey) ";
pahinga;
}
$ Query = "ipasok sa $ databasetable halaga (",'$ newlinemysql ')
SA dobleng key UPDATE
$ Duplicatevals ";
} Ibang {
$ Query = "ipasok sa $ databasetable mga halaga ('$ linemysql')
SA dobleng key UPDATE
$ Duplicatevals ";
}
Gayundin, sa aking form ko idinagdag ng talahanayan pangalan at kung gusto ko ang table na [boolean] "addauto" o hindi bilang isang solong input mula sa isang drop-down (comma separated), pagkatapos ay split ang resulta sa tuktok ng simplecsvimport script.
Panghuli, mayroon kang tandaan upang itakda ang mga ini-index sa database para sa, "SA dobleng ..." sa trabaho, ang mga palugit ng auto ay hindi gagana sa kasong ito, kaya't mayroon kang magtakda ng isang pangalawang index sa talahanayan sa pagdagdag ng auto, ang mga talahanayan na don 't auto pagdagdag at magkaroon ng mga natatanging mga patlang ay gumagana sa solong index kung ang ruta na gusto mong pumunta.
Umaasa ako na ito ay makakatulong isang tao!
Cheers!
Hello,
Ginawa ilang mga pagbabago. . Aking txt file ay may 3 mga hanay na separated sa pamamagitan ng isang "|" (tubo) na character. Ang script ay ipinapakita ang mga data file, bilang ng mga hilera, ngunit hindi ipasok ang mga data sa database. Anumang mga puna?
$ Csvcontent = fread ($ file, $ laki);
fclose ($ file);
$ Salungat = @ mysql_connect ($ dbhost, $ dbusername, $ dbuserpassword) o mamatay (mysql_error ());
@ Mysql_select_db ($ datasource) o mamatay (mysql_error ());
$ Lineseparator = "\ n";
$ Fieldseparator = "|";
$ Linya = 0;
$ Query = "";
$ Linearray = array ();
$ Count = 0;
foreach (split ($ lineseparator, $ csvcontent) bilang $ linya) {
$ Count = $ count + 1;
$ Linya + +;
$ Linya = trim ($ linya, "\ t");
$ Linya = str_replace ("\ r ","",$ linya);
/************************************
Ang linyang ito escapes ng mga espesyal na character. alisin ito kung entry ay escaped sa csv file
************************************/
$ Linya = str_replace ("'"," \ '", $ linya);
/*************************************/
$ Linearray = sumabog ($ fieldseparator, $ linya);
$ Linemysql = pumutok sa loob (""",$ linearray);
kung ($ addauto)
$ Query = "ipasok sa mga tagapagpahiwatig ng halaga ('$ count', '$ linemysql');";
iba
$ Query = "ipasok sa tagapagpahiwatig ng halaga ('$ linemysql');";
$ Query .= $ query. "\ N";
@ Mysql_query ($ query) o mamatay (mysql_error ());
echo "$ linemysql \ n";
}
hindi ko na ito ng kung paano ito gumagana mula sa isang file ng control. nangangahulugan unang-browse at pumili ng isang file at pagkatapos ay isumite na kung saan kailangan i upang mabago
Ito ay Kapaki-pakinabang na code para sa akin ..
salamat.
Paano ko makukuha ang browse file sa halip ng-type ang buong pangalan path ..
Mangyari lamang na tulong sa.
salamat
Salamat, ang code na ito ay talagang nakatulong!
Paano ko baguhin ito upang payagan ang form ng isang upang maipakita kung saan ang gumagamit ay browses at pinipili ang csv file na na-import papunta sa table?
At din kung paano maaari kong gawin ito upang ang bawat oras na ang isang bagong file ay isinumite ito ay sasapaw sa anumang kasalukuyang naka-imbak sa table?
Maraming salamat
[...] Na mayroong ilang mga magandang katangian na maaari kong gamitin upang makatulong na ako magturo ng mga tao PL / SQL at XML. ITips at Tricks PHP script-import ng data ng csv sa mysqlPHP script-import ng data ng csv sa MySQL ... [...]
Hi lahat,
Paano ko maglaman ng mga quote csv na ito sa petsa "araw, petsa ng buwan, 2010" at ang estado "prov, estado" sa isang haligi sa aking data base? Nakikita ko maraming mga halimbawa ngunit hindi ako makakuha ng ito sa trabaho. tulong anumang magandang.
AK, 10037591,1, "Martes, Marso 9, 2010 15:55:16", 59.7151, -151.4434,2.7,75.90,32, "Tangway ng Kenai, Alaska"
thx
@ Kish
ang kasalukuyang code ay hindi payagan ang pag-browse para sa /-upload ng file.
Maaari mo lang ilagay ang CSV file sa parehong directory bilang ang script ng PHP, at lamang na itakda ang $ csvfile variable na katumbas ng pangalan ng file (walang path)
@ Gary
maaari mong gamitin ang isang @ mysql_query ("pungusan $ databasetable"); karapatan pagkatapos ng @ mysql_select_db statement.
Ngunit maging maingat ng pagkilos na ito ay lipulin ng data at hindi baligtaran.
Paano ko laktawan ang unang linya / hilera na kung saan ay isang header sa csv file at ipasok ang magpahinga ng ang data sa db?
Tulad Gary, gusto kong maging patungan ang isang umiiral na record, ngunit sa pamamagitan ng pag-update ito, hindi tinatanggal ang lahat ng mga data sa db. SP lugar sa paligid dito:
kung ($ addauto)
$ Query = "ipasok sa $ databasetable halaga (",'$ linemysql');";
iba
$ Query = "ipasok sa $ databasetable na mga halaga ('$ linemysql');";
Paano Gusto ko suriin upang makita kung umiiral ang rekord at pagkatapos ay I-update sa halip kaysa Ipasok?
Ang script ay nagbabasa ng isang dagdag na linya mula sa csv file. eg kung ang csv file ay may 25 mga tala Ipinapakita nito may 26 mga talaan. Puwede ninyo bang sabihin sa akin kung saan ako pagpunta maling?
Naidagdag ko upang suriin kung ito ay isang unang linya at magpatuloy ang loop kung ang unang linya nito.
salamat
Ang mga sumusunod ay ang lokohin ang para sa akin:
Load ang data LOCAL INFILE LOW_PRIORITY
'C: \ \ Dokumento at Mga Setting \ \ Administrator \ \ Desktop \ \ SigmaS1.csv'
SA TALAAN `mydb`. `Mytable`
FIELDS escaped NG '\ \'
Itinigil NG ','
Opsyonal na nakapaloob NG '"'
Linya tinapos NG '\ r \ n'
(`User`, `pwd`, `sno`, `Halaga`, `ActiveRec`);
Ito ay masyadong kapaki-pakinabang sa akin ... ngunit kailangan ko upang gumawa ng pagbabago para sa pagbabasa sa mga malalaking file. Ako ay nalilito sa una, ngunit pagkatapos ay natanto ang script-load ng ang buong file sa memory (right?). Kaya dito ay isang customized na bersyon ng code, na bumabasa ng mga linya sa isa sa sa isang oras. bumabasa sa file na hitsura
simulan ang file:
2,3, -1
1, -2,4
dulo file (na may mas maraming mga halaga). i nais ang bawat linya sa isang entry ng talahanayan at isang id na may linya ang bilang, pati na rin ang unang id na kumakatawan sa laki ng table (na hindi magbabago mamaya).
<? Php
/********************************/
/ * Code sa http://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/ * I-edit ang mga entry sa ibaba upang ipakita ang mga naaangkop na halaga
/********************************/
$ Databasehost = "localhost";
$ Databasename = "tomoku";
$ Databaseusername = "root";
$ Databasepassword = "root";
$ Fieldseparator = "\ n";
$ Lineseparator = "\ n";
/ / Code na ito ay bumabasa ng mga file tatami sa database
$ Salungat = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) o mamatay (mysql_error ());
@ Mysql_select_db ($ databasename) o mamatay (mysql_error ());
/ / Ito loop sa loob ng isang grupo ng mga file
para sa ($ r = 2; $ r <14; $ r + +) {
para sa ($ c = $ r; $ c
Kung ako limitado sa mga ma-access ang harddrive client kung paano ako pagpunta upang i-upload ang csv file sa Halimbawa server.for maaari naming itakda ang default na halaga sa file upload control
Kahanga-hanga script ngunit nagkakaroon ako ng reoccurring problema.
Pagkatapos tumakbo ko ang script, sabi ni "Natagpuan ng isang kabuuang 1 talaan sa csv file na ito.".
Tumingin ako pabalik sa aking table at ito ay nagpapakita ng blangkong.
Ako check upang tiyakin na nagkaroon ang karapatan bilang ng mga haligi at mayroong.
Mangyaring tulungan!
Salamat,
Coulton
Kung nais mong maiwasan ang pagpasok ng unang hilera, mag-play sa kontra, halimbawa:
$lines = 1; ( The value for the counter is 1)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) bilang $ linya) {
$lines++; ( Assigns the first line #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. Help.
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');”;
iba
$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?
Hi,
Getting this error. how to resolve this?
Error:
File is not writable, check permissions. Found a total of 13 records in this csv file.
Salamat
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!
Hi,
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 = “http://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());
$ Linya = 0;
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) bilang $ linya) {
$ Linya + +;
$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
************************************/
$ Linya = str_replace ("'"," \ '", $ linya);
/*************************************/
$ Linearray = sumabog ($ fieldseparator, $ linya);
$ Linemysql = pumutok sa loob ("','",$ linearray);
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
iba
$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. Salamat sa iyo!
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”;
}
iba
{
?>
Type file name to import:
Petsa
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……..
Send 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.? Salamat.
@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. Anumang mga ideya?
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
Hi,
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
keywords
@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.
Website URL:
Database Name:
Database User Name:
Database Password:
Path of Directory containing files to upload:
/********************************/
Question
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 http://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.
/ * Itakda ang 1 para sa yes at 0 para sa walang. Pansin: hindi nakatakda sa 1 kung hindi ka sigurado.
/* 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? Kung oo set $-save sa 1.
/ * Pahintulot sa file ay dapat nakatakda sa 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) bilang $ linya) {
$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) bilang $ linya) {
$ Linya + +;
$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
************************************/
$ Linya = str_replace ("'"," \ '", $ linya);
/*************************************/
$ Linearray = sumabog ($ fieldseparator, $ linya);
$ Linemysql = pumutok sa loob ("','",$ linearray);
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
iba
$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
salamat
@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());
$ Linya = 0;
$queries = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$ Linya + +;
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 = sumabog ($ fieldseparator, $ linya);
$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);
Thank you,
@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');
// http://www.ihappyapps.com/DataFolder/loader.php
/********************************/
/* Code at http://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());
$ Linya = 0;
$ Query = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$ Linya + +;
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
********************************************************/
$ Linya = str_replace ("'"," \ '", $ linya);
/*******************************************************/
$ Linearray = sumabog ($ fieldseparator, $ linya);
$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) ?
and another one with $fielddelimiter (” or nothing)
My ideia was a combobox with $fieldseparator (, or
Salamat in advance.
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.
Thank you very much. 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.
Please help.
Salamat.
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
Salamat!
It works like a charm!
Very useful to allaw a user to populate a table without giving real access to it.
Thanks again
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. Salamat.
Hi,
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.
Hi im newbie on php. and need help. i need to load a single csv file and feed 2 mysql tables. but the data in csv file dont have the same structure as in mysql table. also have problems with date format and commas inside data.
mysql table1
id,name,email,status
mysql table 2
id,book_name,date_book_out,date_book_in
csv file
10052,”MikeParker”,”mike@email.net”,”active”
10052,”Before the Season Ends, rt526″,2011/01/10,2011/01/25
Salamat
Hi guys,
Please help me in this script. It only inserts 240 records in database.
It's not such a good script… how to deal with a few thousends or more records?
It aint nice to the database to run thousends of queries when you could do a much better import by storing maybe 1000 lines in 1 import..
I have read your post thoroughly and got mind blowing information…. Please send me mail if your are going to improve something advance..
Thanks..
natural suppliments
I just want to thank you for sharing your information and your website, this is simple, but good article I have ever seen, I like it, and I learned something today! Salamat!
maquinas de bordar
Hy
The script is fine, working great, but i need an advice
My table has 3 colomns:
id, code and name
I allready have some data inserted, and i want to insert only the info that's mesing.
I need to check only by cod. So if the code exists , the scipt shold not inserted.
Thanks in advance for advices.
Best Regards,
Stefan
Thanks for your informations
I've already bookmarked this article and will definitely refer this article
to all my close friends and colleagues. Thanks for posting!