script PHP untuk mengimpor data csv ke mysql
Ini adalah script sederhana yang akan memungkinkan Anda untuk mengimpor data csv ke dalam database Anda. Hal ini datang berguna karena Anda hanya dapat mengedit bidang yang sesuai, meng-upload bersama dengan file csv dan menyebutnya dari web dan akan melakukan sisanya.
Hal ini memungkinkan Anda untuk menentukan pemisah dalam file csv, apakah itu koma, sebuah dll tab ini juga memungkinkan Anda untuk memilih garis pemisah, memungkinkan Anda untuk menyimpan output ke sebuah file (dikenal sebagai dump data sql).
Hal ini juga memungkinkan Anda untuk memasukkan sebuah bidang kosong pada awal setiap baris, yang biasanya sebuah integer kenaikan otomatis primary key.
Script ini berguna terutama jika Anda tidak memiliki phpmyadmin, atau Anda tidak ingin terganggu dengan log in dan lebih memilih solusi beberapa klik, atau Anda adalah seorang pria command prompt.
Pastikan tabel tersebut sudah diciptakan sebelum mencoba membuang data.
Mohon posting komentar Anda jika Anda punya laporan bug.
Great script! Tnx banyak
Hi ...
Saya menghadapi masalah, saat saya menggunakan ini, yang menunjukkan error yang mengatakan
"Usang: Fungsi split () sudah ditinggalkan di C: \ wamp \ www \ test1 \ simplecsvimport.php on line 64
File tidak dapat ditulis, periksa permission. Ditemukan total 41 catatan dalam file csv. "
Pls reply, apa yang salah!
thanks in advance!
Aku benar-benar bingung dengan kode ini!
tapi aku biasa mencoba up!
BTW, bagaimana kode html atau lapangan untuk memanggil kode ini
Terima kasih, importir csv sangat baik.
Tapi aku menemukan satu masalah kecil, hanya bekerja dengan file csv dengan struktur: "field1", "Field2", "field3", dll tapi saya Hava file CSV seperti ini: field1, Field2, filed3, dll
Satu-satunya yang bisa mengubah adalah $ fieldseparator tapi bagaimana saya bisa 'memberitahu' script yang file tidak menggunakan "(pembatas lapangan)?
ideia saya adalah seorang combobox dengan $ fieldseparator (, atau dan satu lagi dengan $ fielddelimiter ("atau tidak)
Thanks in advance.
Setiap gagasan tentang bagaimana untuk mendapatkan script ini bekerja untuk bidang yang tertutup dengan tanda kutip ganda sehingga bidang dengan koma di dalamnya tidak mendapatkan dibaca sebagai sebuah entri baru?
Saya memiliki data yang mencakup koma seperti jumlah dolar dan bagian komentar di mana pengguna mungkin telah menggunakan koma. Saya perlu seluruh bidang impor dan skrip ini memperlakukan mereka sebagai bidang baru.
@ Mark Cloyd
"Alamat = VALUES (alamat)
Saya mendapatkan error di sini sebagai kesalahan Parse: syntax error, tak terduga '='
@ Joofoo
Saya telah dimuat kode Anda tapi saya tidak mendapatkan info diperbaharui di database MySQL ...
CSV berisi:
Header - username>, sandi, pesan, email, gambar, tanggal
ROW2 -> Bill, dude,,,,
Row3 -> Jane, gal,,,,
Row4 -> David, anak,,,,
Dan di sini adalah kode ...:
<? Php
/ / Set-up dari file iphonelogin.php di folder "remote" ...
/ * Terhubung ke db * /
/ / $ Link = mysql_connect ('ronbo.db.6405862.hostedresource.com', 'ronbo', 'Pepper0689') or die ('Tidak dapat terhubung ke DB');
/ / Mysql_select_db ('ronbo', $ link) or die ('Tidak dapat memilih DB');
/ / https://www.ihappyapps.com/DataFolder/loader.php
/********************************/
/ * Kode di https://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/ * Edit entri di bawah ini untuk mencerminkan nilai-nilai yang sesuai
/********************************/
$ Databasehost = "dbhost";
$ Databasename = "Nama";
$ Databasetable = "tabel";
$ Databaseusername = "username";
$ Databasepassword = "password";
$ Fieldseparator = ",";
$ Lineseparator = "\ n";
$ Csvfile = "spreadsheet.csv";
/********************************/
$ Addauto = 1;
/********************************/
$ Simpan = 0;
$ Outputfile = "output.sql";
/********************************/
if (file_exists ($ csvfile)!) {
echo "Server mendapat permintaan Anda, namun file CSV Anda ingin memuat ke dalam database tidak hadir ... .. \ n";
exit;
}
$ Chunksize = 1 * (1024 * 1024);
$ File = fopen ($ csvfile, "rb");
if ($ file!) {
echo "Error membuka file data \ n.";
exit;
}
$ Size = filesize ($ csvfile);
if ($ ukuran!) {
echo "Berkas kosong \ n.";
exit;
}
$ Con = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) or die (mysql_error ());
@ Mysql_select_db ($ databasename) or die (mysql_error ());
$ Baris = 0;
$ Query = "";
while (! feof ($ file)) {
$ Csvline = fgets ($ file, $ chunksize);
$ Baris + +;
if ($ baris <2) melanjutkan;
$ Baris = trim ($ csvline, "\ t");
$ Baris = str_replace ("\ r ","",$ baris);
/************************************************* ************************************************** *********
Baris ini lolos karakter khusus. menghapusnya jika entri sudah lolos dalam file csv
************************************************** ************************************************** ********/
$ Baris = str_replace ("'"," \ '", $ baris);
/************************************************* ************************************************** ********/
$ Linearray = meledak ($ fieldseparator, $ line);
$ Linemysql = meledak linearray ("','",$);
$ Query insert = "ke nilai databasetable $ ('$ linemysql');";
if ($ simpan) $ query $ query .=. "\ N";
@ Mysql_query ($ query);
echo $ baris "\ n".;
}
fclose ($ file);
$ Baris -= 3;
@ Mysql_close ($ con);
<>
Aku benar-benar bisa menggunakan bantuan dalam mendapatkan ini untuk bekerja ...
Ron
@ Roy
Saya diubah script anda, sehingga mengkonsumsi memori jauh lebih sedikit saat memproses file besar (itu menghantam batas memori php ketika saya mencoba untuk menggunakannya pada file CSV 100mb). Perubahan adalah sebagai berikut:
$chunksize = 1*(1024*1024);
$file = fopen($csvfile,"rb");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$ Size = filesize ($ csvfile);
if ($ ukuran!) {
echo "Berkas kosong \ n.";
exit;
}
$ Con = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) or die (mysql_error ());
@ Mysql_select_db ($ databasename) or die (mysql_error ());
$ Baris = 0;
$ Query = "";
while (! feof ($ file)) {
$ Csvline = fgets ($ file, $ chunksize);
$ Baris + +;
if ($ baris <2) melanjutkan;
$ Baris = trim ($ csvline, "\ t");
$ Baris = str_replace ("\ r ","",$ baris);
/************************************************* ************************************************** *********
Baris ini lolos karakter khusus. menghapusnya jika entri sudah lolos dalam file csv
************************************************** ************************************************** ********/
$ Baris = str_replace ("'"," \ '", $ baris);
/************************************************* ************************************************** ********/
$ Linearray = meledak ($ fieldseparator, $ line);
$ Linemysql = meledak linearray ("','",$);
$ Query insert = "ke nilai databasetable $ ('$ linemysql');";
if ($ simpan) $ query $ query .=. "\ N";
@ Mysql_query ($ query);
echo $ baris "\ n".;
}
fclose ($ file);
$ Baris -= 3;
@ Mysql_close ($ con);
Terima kasih,
@ Khaled A
Bagaimana saya bisa mengekspor UTF8 excel untuk output.sql
terima kasih
Aku mencoba script tetapi output.sql adalah writting hal aneh,
masukkan ke dalam nilai test_excel ('PK |!?????????????? Q K5 K5 q Q q Q K5 q ....
seperti hal-hal ini
bagaimana saya bisa memperbaiki masalah ini. format khusus untuk excel sheet?
Hi guys, hanya ingin memberitahu Anda semua tahu bahwa aku telah menemukan seseorang untuk menulis saya program yang sebenarnya saya butuhkan.
@ Warren
/********************************/
File ini meliputi perubahan yang dibuat percobaan oleh Warren (bukan programmer) pada 28 Des 2010 dan seterusnya berdasarkan komentar di situs sumber dan info lainnya sehingga membuat program ini menjadi salah satu yang ia butuhkan. Hal ini sangat tidak lengkap. Bantuan yang paling dihargai dan sangat dibutuhkan.
Baris yang ditambahkan untuk membuat kotak input untuk nama database URL situs web dan password dll
/********************************/
Selamat Datang ke Server Upload Utility
Program ini berlangsung dari PC Anda untuk mengisi dua meja kosong di Database MySQL baru di situs Anda dengan: meng-upload setiap nama berkas kurang ekstensi, dengan nomor unik di depan sebagai counter, untuk keywords_categories meja, lalu kemudian menetapkan nomor 1 di kolom kosong di depan Colum pertama data dari file tersebut, dan meningkatkan nomor dengan satu untuk setiap file selanjutnya diolah dari direktori tersebut, sehingga nomor assigend ke nama kategori dalam tabel sesuai dengan kata kunci milik itu yang kemudian upload ke tabel kata kunci.
Hal ini dilakukan untuk semua file csv di direktori tertentu ke dalam.
Hal ini mengabaikan lima baris pertama dalam file csv Anda.
Website URL:
Nama Database:
Database User Name:
Database Password:
Jalur Direktori yang berisi file untuk meng-upload:
/********************************/
Pertanyaan
Bagaimana saya bisa atas data dari kotak masukan ke dalam program agar sesuai dengan yang diminta di bawah?
/********************************/
<? Php
/********************************/
Line ditambahkan untuk mencegah timeout pada file yang lebih besar.
/********************************/
set_time_limit (0);
/********************************/
Dapatkan file nama-nama file yang akan diproses, menghapus ekstensi nama file kemudian menggunakannya untuk meng-upload sebagai nama kategori untuk keywords_categories meja.
/********************************/
/********************************/
Menghapus file perpanjangan nama
disalin dari perlmonks www org / node_id = 151232?
/********************************/
sub parse_out_extension {
die ("Tidak ada nama berkas untuk membaca \ n.") if (@ _!);
saya ($ file) = @ _;
saya @ lembar;
peta {push (@ potong, $ _)} split (/ \ /, $ file.);
saya $ akhir = pop (@ buah);
$ File = ~ s / \ $ akhir / /.;
return ($ file) jika $ file;
/********************************/
/ * Original kode di https://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/ * Edit entri di bawah ini untuk mencerminkan nilai-nilai yang sesuai
/********************************/
$ Databasehost = "localhost";
$ Databasename = "test";
$ Databasetable = "contoh";
$ Databaseusername = "test";
$ Databasepassword = "";
$ Fieldseparator = ",";
$ Lineseparator = "\ n";
$ Csvfile = "filename.csv";
/********************************/
/ * Apakah Anda ingin menambahkan field ampty pada awal catatan ini?
/ * Catatan oleh Warren dalam kasus kata kunci yang merupakan kolom pertama dari data di tiap file, pada file dengan dasar file ini coum tempat baru kosong din frot kata kunci perlu diubah sehingga menangkap nomor ditetapkan ke nama kategori yang terdiri dari nama file kurang perpanjangan dan tempat-tempat di kolom ini baru pertama kosong.
/ * Ini berguna jika Anda memiliki sebuah tabel dengan kolom pertama adalah sebuah integer auto_increment. Catatan oleh Warren. Ini adalah apa yang butuhkan dalam kasus exteniosn nama file yang kurang yang upoaded untuk keywords_categories meja.
/ * Dan file csv tidak memiliki seperti lapangan kosong sebelum catatan.
/ * Set 1 untuk ya dan 0 untuk tidak ada. PERHATIAN: jangan set ke 1 jika Anda tidak yakin.
/ * Ini bisa dump data dalam bidang salah jika bidang ini tambahan tidak ada dalam tabel. Catatan oleh Warren kemungkinan tidak perlu file ini saya kasus saya tapi hanya menebak di bagian saya tapi perlu melihat kebutuhan jika ada.
/********************************/
$ Addauto = 1;
/********************************/
/ * Apakah Anda ingin menyimpan query mysql di file? Jika ya set $ simpan ke 1.
/ * Ijin pada file harus di set ke 777. Entah meng-upload contoh file melalui ftp dan
/ * Mengubah hak akses, atau mengeksekusi pada prompt: output.sql touch & & chmod 777 output.sql
/********************************/
$ Simpan = 0;
$ Outputfile = "output.sql";
/********************************/
if (file_exists ($ csvfile)!) {
echo "File tidak ditemukan. Pastikan Anda tentukan jalan yang benar \ n ".;
exit;
}
$ File = fopen ($ csvfile, "r");
if ($ file!) {
echo "Error membuka file data \ n.";
exit;
}
$ Size = filesize ($ csvfile);
if ($ ukuran!) {
echo "Berkas kosong \ n.";
exit;
}
$ Csvcontent = fread ($ file, $ ukuran);
fclose ($ file);
$ Con = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) or die (mysql_error ());
@ Mysql_select_db ($ databasename) or die (mysql_error ());
/********************************/
Untuk menghindari memasukkan empat baris pertama dari teks adveristing header dan sebuah baris kosong. Garis sama dengan nol kode diganti dengan kode di bawah ini.
/********************************/
$ Baris = 1; (Nilai untuk counter 1)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) sebagai $ baris) {
$ Baris + +; (Menetapkan baris pertama # 2 (header)
if ($ baris> = 5) {(Mulai di # 5 "apa pun yang lebih tinggi atau sama dengan 5?)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) sebagai $ baris) {
$ Baris + +;
$ Baris = trim ($ line, "\ t");
$ Baris = str_replace ("\ r ","",$ baris);
/************************************
Baris ini lolos karakter khusus. menghapusnya jika entri sudah lolos dalam file csv
************************************/
$ Baris = str_replace ("'"," \ '", $ baris);
/*************************************/
$ Linearray = meledak ($ fieldseparator, $ line);
$ Linemysql = meledak linearray ("','",$);
if ($ addauto)
$ Query = "insert into nilai $ databasetable (",'$');"; linemysql
lain
$ Query insert = "ke nilai databasetable $ ('$ linemysql');";
$ Query $ query .=. "\ N";
/************************************
Ini sedikit kode di bawah ini telah ditambahkan ke dalam sekarang menunjukkan pesan kesalahan.
************************************/
$ Result = mysql_query ($ query);
/ / Periksa hasil
/ / Ini menunjukkan permintaan yang sebenarnya dikirim ke MySQL, dan kesalahan. Berguna untuk debugging.
if ($ result!) {
$ pesan = 'tidak valid query:'. mysql_error (). "\ N";
$ Pesan 'Whole query:' .=. $ Query;
mati ($ pesan)
}
@ Mysql_close ($ con);
if ($ simpan) {
if (! is_writable ($ outputfile)) {
echo "File tidak dapat ditulis, izin periksa \ n.";
}
else {
$ File2 = fopen ($ outputfile, "w");
if ($ file2!) {
echo "Kesalahan menulis ke file output \ n.";
}
else {
fwrite ($ file2, $ query);
fclose ($ file2);
}
}
}
echo "Ditemukan total $ baris catatan dalam csv file ini \ n.";
?>
Hanya sedikit koreksi untuk meminta saya, kedua tabel dalam database MqSQL saya sebutkan sebenarnya disebut:
keywords_categories
kata kunci
@ Warren
Juga, rasa ingin tahu hanya keluar dari bisa juga proses file txt, (yang baru saja daftar kata di dalamnya) dengan cara yang sama?
(Saya baru di ini, dan tahu aku mungkin bertanya banyak, sehingga jika seseorang bisa mengambil proyek kecil di bagi saya, jika cocok, mungkin kita bisa mendiskusikan saya membayar jumlah yang kecil untuk waktu mereka dalam membuat perubahan memenuhi kebutuhan saya Tolong beritahu saya.?)
e-mail saya adalah: wr.spence @ hotmail.com
Saya bukan seorang programmer. Saya melihat skrip Anda dan mungkin dekat dengan apa yang saya butuhkan, atau mungkin bisa membentuk dasar dari apa yang saya butuhkan, saya tidak yakin.
Saya perlu melakukan upload fungsi yang sama berulang lagi, tapi dari sub-direktori yang berbeda setiap kali dari hard drive saya, untuk daftar file csv, dan ke DB MySQL berbeda setiap kali (di situs differret setiap kali). Dalam kebanyakan kasus db tidak akan memiliki data apapun di dalamnya, tapi akan ideal (tapi tidak penting) jika skrip masih bisa bekerja dengan db yang punya data, tanpa mempengaruhi data yang ada).
Saya perlu untuk login ke db di server (harus meminta saya untuk URL situs dan nama pengguna dan password db, dll).
Aku butuh sesuatu yang memungkinkan saya mencari dan memilih nama direktori pada hard drive saya, atau masukkan.
Kemudian setiap proses file csv di direktori, satu setelah lainnya, sebagai berikut:
Pada setiap file saya perlu untuk terlebih dahulu mengambil nama file (kurang ekstensi) dan meng-upload ke db dalam kategori tabel. Dalam tabel tersebut berisi tombol angka yang kemudian ditugaskan ke nama itu.
Saya kemudian perlu script untuk meng-upload hanya Colum kata (1 Colum data) dari file tersebut ke kata-kata meja, dan menambahkan nubmer cocok untuk nama kategori dari file pertama.
Perlu dicatat bahwa file CSV sering berisi tiga baris teks header dan baris kosong, keempat yang saya inginkan tidak diabaikan dan upload. Seringkali ada baris kosong di eend te dari file saya juga ingin mengabaikan, mereka, serta mengabaikan setiap kolom lain yang mungkin atau mungkin tidak di file csv. Dalam beberapa kasus file csv tidak mungkin memiliki header atau kolom lainnya.
Kemudian file selanjutnya, sampai kehabisan file dalam direktori.
Lalu aku akan menyukainya memberitahu saya, "Proses selesai." Dan jika ada kesalahan untuk menceritakan.
Dapatkah salah satu dari kalian membantu saya dengan ini?
Terima kasih untuk berbagi excel ke mysql script, ini sangat berguna bagi saya.
ya bekerja kode tapi nw saya mendapatkan data saya tertutup dalam tanda kutip @ Suman
@ Pruthvi
Hi,
Silakan gunakan kode yang diberikan dibawah ... ...
Parut Kode Ini benar-benar bermanfaat bagi semua pengembang PHP.
Anda bisa menjelaskan kode Anda Anda ingin mengganti @ mysql_query ($ query); dengan pernyataan u memberi tapi menunjukkan kesalahan $ pesan tidak terdefinisi @ Ikan Andrew
masalah yang sama dengan saya @ Andrew Ikan
perkembangan kode dapat mendeteksi tidak ada baris dalam file csv namun tidak ditampilkan dalam tabel
kode ini kembali pernyataan bahwa hal itu tak bisa menemukan file csv ...
mungkin wat masalah ....
Oke, menemukan masalah. Saya telah mispelt nama tabel. Tapi hanya menemukan masalah ketika saya telah menambahkan kode berikut ini yang akan menghasilkan kesalahan jika sql gagal. Saat ini script tidak mengatakan apakah ada menjadi masalah.
Jadi ubah baris
@ Mysql_query ($ query);
untuk semua hal berikut: -
$ Result = mysql_query ($ query);
/ / Periksa hasil
/ / Ini menunjukkan permintaan yang sebenarnya dikirim ke MySQL, dan kesalahan. Berguna untuk debugging.
if ($ result!) {
$ pesan = 'tidak valid query:'. mysql_error (). "\ N";
$ Pesan 'Whole query:' .=. $ Query;
mati ($ pesan)
Harapan yang membantu seseorang. Hal itu saya.
AJ
@ Andrew Ikan
Ketika saya menjalankan script ini menggunakan csv yang saya tahu impor dengan benar menggunakan PHP Admin, skrip dijalankan, melaporkan jumlah yang benar dari baris dengan pesan "Ditemukan total 193 record dalam file csv." Tapi tidak ada data yang muncul dalam meja. Saya telah membuat perubahan pada csv sehingga aku dapat melihat apakah data yang dimasukkan ke dalam tabel dan tidak. Ada gagasan?
AJ
My CSV file impor juga memiliki tanda kutip ganda sekitar setiap bidang (terutama untuk menghindari masalah jika saya perlu diimpor ke Excel sehingga tidak merusak data), jadi saya punya masalah di mana ia memasukkan catatan dengan tanda kutip di sekitar data. Saya dilucuti semua tanda kutip ganda dengan menambahkan baris ini:
$ Baris = str_replace (baris "\ "","",$);
setelah baris ini:
$ Baris = str_replace ("\ r ","",$ baris);
dan baris baru menggantikan tanda kutip ganda dengan apa-apa. Ini sama dengan baris sebelum kecuali itu menghapus \ "daripada \ r (tanda kutip ganda bukan tombol enter).
@ Rapi
Sebuah program kecil yang hebat.
Apakah ada cara untuk mengganti data dalam sel misalnya. 'Kota' di csv dan mengubahnya ke nilai dari halaman sebelumnya seperti $ _SESSION atau $ nilai _POST?
Ini bagus ... sangat mudah untuk diimplementasikan. Sekarang harus mengetahui bagaimana menggunakan script ini atau mirip dengan meng-upload. Xls file bersama dengan file. Csv
@ Mike
Dapatkah Anda coba tambahkan:
set_time_limit (0);
tepat di awal? (Tepat setelah tag pembuka php)
@ Eksklusif Tutorial
Apakah ada cara untuk memilikinya belum saatnya keluar? it works great dengan 100k catatan, tapi ketika saya pergi untuk sesuatu yang besar seperti mil atau lebih, berlangsung selama sekitar 20 detik kemudian pergi ke layar kosong dan iklan tidak ada catatan.? Terima kasih.
Setelah masalah yang sama persis, dapat anyone help please?
HI teman-teman,
Aku butuh bantuan mendesak dari Anda ... Jadi baik membantu saya di sini adalah kode ...
Mempersiapkan file HTML. Tetapi saya membutuhkan solusi php ... Mohon bantuan untuk saya ... ... ..
Kirim SMS
Penerima Nomer HP:
+91
Buku Telepon
Upload Excel Berkas:
<!-->
<Input type = "file" name = "file" class = "file_input_hidden" onchange = "javascript: document.getElementBy
Sender ID:
:
YOGA
GRAFS
Mobitel
var frmvalidator = baru Validator ('freesms2');
frmvalidator.addValidation ("frno", "req", "Masukkan nomor ponsel");
frmvalidator.addValidation ("frno", "num", "field nomor Handphone harus mengandung Bilangan");
frmvalidator.addValidation ("frno", "minlength = 10000", "nomor Mobile harus 10000 digit");
frmvalidator.addValidation ("message3", "req", "Masukkan teks SMS");
dengan best regards,
Ravi Kumar
<? Php
newbal = '0 '$;
termasuk "conn.php";
if (isset ($ ['submit'] _POST))
{
$ Filename = $ _POST ['filename'];
$ Handle = fopen ("$ filename", "r");
while (($ data = fgetcsv ($ handle, 1000, ","))! == FALSE)
{
$ Sql5 = mysql_query ("* pilih dari item item data = 'di mana $ [0 ]'");
$ Num = mysql_num_rows ($ sql5);
if ($ num == 0)
{
$ Import = "INSERT data ke dalam butir (item, gweight, dweight) nilai ('$ [0 ]','$ data [1 ]','$ data [2 ]')";
mysql_query ($ impor) or die (mysql_error ());
}
else {
echo "$ data [0] keluar";
}
}
fclose ($ handle);
print "Impor dilakukan";
}
lain
{
?>
Ketik nama file yang akan diimpor:
Tanggal
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 ();
?>
bekerja dengan baik pada ketika saya mengupload file csv di localhost, tetapi menunjukkan kesalahan file yang hilang saat berjalan di server.please membantu saya, terima kasih sebelumnya
Saya rasa ini adalah terbaik untuk csv keranjang belanja ke dalam sql.
kaundo le Doy Descarga saya aparecen todos los muchos ritsleting los archivos en una sola ubico carpeta? ¿
@ Zeshan
menggunakan meledak bukan split
Usang: Fungsi split () sudah ditinggalkan di E: \ wamp \ www \ floodpk2 \ admin \ simplecsvimport.php on line 63
File tidak dapat ditulis, periksa permission. Ditemukan total 1498 record dalam file csv.
plz membantu saya mendesak
8pills.com adalah one stop solusi perawatan kesehatan Anda. 8pills.com memberikan terbaik dari kelas Generik dan obat-obatan Branded.
i am menghadapi pemberitahuan bawah-
Notice: Undefined offset: 1 di C: \ wamp \ www \ New Folder (2) \ exl8.php on line 20
Notice: Undefined offset: 2 di C: \ wamp \ www \ New Folder (2) \ exl8.php on line 20
Notice: Undefined offset: 2 di C: \ wamp \ www \ New Folder (2) \ exl8.php on line 20
Ini bekerja sangat baik. Terima kasih!
Berikut adalah kode btw,
$ Databasehost = "localhost";
$ Databasename = "database";
$ Databasetable = "tabel";
$ Databaseusername = "admin";
$ Databasepassword = "admin";
$ Fieldseparator = ",";
$ Lineseparator = "\ n";
$ Csvfile = "https://linktosite/";
$ Addauto = 0;
$ Simpan = 0;
$ Outputfile = "output.sql"; / / jika simpan pada (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 ());
$ Baris = 0;
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) sebagai $ baris) {
$ Baris + +;
$ Baris = trim ($ line, "\ t");
$ Baris = str_replace ("\ r ","",$ baris);
/************************************
Baris ini lolos karakter khusus. menghapusnya jika entri sudah lolos dalam file csv
************************************/
$ Baris = str_replace ("'"," \ '", $ baris);
/*************************************/
$ Linearray = meledak ($ fieldseparator, $ line);
$ Linemysql = meledak linearray ("','",$);
if ($ addauto)
$ Query = "insert into nilai $ databasetable (",'$');"; linemysql
lain
$ Query insert = "ke nilai databasetable $ ('$ linemysql');";
$ Query $ query .=. "\ N";
@ Mysql_query ($ query);
}
@ Mysql_close ($ con);
if ($ simpan) {
if (! is_writable ($ outputfile)) {
echo "File tidak dapat ditulis, izin periksa \ n.";
}
else {
$ File2 = fopen ($ outputfile, "w");
if ($ file2!) {
echo "Kesalahan menulis ke file output \ n.";
}
else {
fwrite ($ file2, $ query);
fclose ($ file2);
}
}
}
echo "Ditemukan total $ baris record di file csv. ditambahkan ke DB \ n ".;
Hi,
Saya menggunakan script ini untuk mengimpor csv kita inginkan untuk mysql.
Satu-satunya masalah saya punya, adalah bahwa tanda kutip "" juga dimasukkan dalam tabel saya
Delimiter:, (komma)
Lampiran: "(aanhalingsteken)
Baris baru: \ r \ n
Nice Work!
Aku hanya punya pertanyaan.
Apakah mungkin untuk menggunakan karakter lebih ke meledak komando dalam script?
Saya allso perlu bahwa ada pemisahan dengan. dan;
Terima kasih banyak jika seseorang telah ide!
Saya menggunakan kode ... ... ... Its terlalu mudah untuk menerapkannya pada situs saya ... ..
Terima kasih banyak ..
Saya ingin lebih beberapa kode php ... ...
Untuk mengkonversi halaman di pdf ...
Hi,
Mendapatkan kesalahan ini. bagaimana mengatasi hal ini?
Error:
File tidak dapat ditulis, periksa permission. Ditemukan total 13 catatan dalam file csv.
Terima kasih
Haan
Hmm .. i got kesalahan seperti ini "Berkas tidak dapat ditulis, izin periksa. Ditemukan total 2 record di file csv "tahu apa yang salah.?
Hmm .. i got kesalahan seperti ini "Berkas tidak dapat ditulis, izin periksa. Ditemukan total 2 record di file csv "tahu apa yang salah.?
Untuk melompat baris pertama / baris yang merupakan header di file csv melakukan ini:
... ..
if ($ baris> 1) {
if ($ addauto)
$ Query = "insert into nilai $ databasetable (",'$');"; linemysql
lain
$ Query insert = "ke nilai databasetable $ ('$ linemysql');";
$ Query $ query .=. "\ N";
@ Mysql_query ($ query);
}
Aku script ini berjalan baik di bawah domain yang berbeda. Kemudian ketika saya pindah itu, download tugas cron file csv, toko, dan kemudian menghapusnya tapi doesnt meng-upload ke mysql. Ketika saya melihat file import.php dan mencoba untuk menjalankannya saya mendapatkan error mengatakan tidak dapat menemukan file pastikan Anda memiliki jalan yang benar. Bantuan.
Jika Anda ingin menghindari memasukkan baris pertama, hanya bermain dengan counter, misalnya:
$ Baris = 1; (Nilai untuk counter 1)
$ Query = "";
$ Linearray = array ();
foreach (split ($ lineseparator, $ csvcontent) sebagai $ baris) {
$ Baris + +; (Menetapkan baris pertama # 2 (header)
if ($ baris> = 3) {(Mulai di # 3 "sesuatu yang lebih tinggi atau sama dengan 3")
script Wonderful tetapi saya mengalami masalah reoccurring.
Setelah saya menjalankan script, ia mengatakan "Ditemukan total 1 catatan dalam file. Csv".
Aku melihat kembali ke meja saya dan itu menunjukkan kosong.
Saya diperiksa untuk memastikan ada nomor yang benar dari kolom dan ada.
Please help!
Terima kasih,
Coulton
Jika saya dibatasi untuk mengakses harddisk klien bagaimana saya akan meng-upload file csv ke contoh server.for kita bisa mengatur nilai default ke file kendali upload
Hal ini sangat berguna bagi saya ... tapi saya perlu membuat modifikasi untuk membaca file besar. Aku bingung pada awalnya, tetapi kemudian menyadari beban script seluruh file ke dalam memori (kanan?). Jadi di sini adalah versi disesuaikan kode, yang berbunyi baris dalam satu per satu. berbunyi dalam file yang terlihat seperti
mulai file:
2,3, -1
1, -2,4
file akhir (dengan nilai lebih banyak). saya ingin setiap baris menjadi entri tabel dan id dengan nomor baris, serta id pertama mewakili ukuran meja (yang tidak akan berubah nanti).
<? Php
/********************************/
/ * Kode di https://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/ * Edit entri di bawah ini untuk mencerminkan nilai-nilai yang sesuai
/********************************/
$ Databasehost = "localhost";
$ Databasename = "tomoku";
$ Databaseusername = "root";
$ Databasepassword = "root";
$ Fieldseparator = "\ n";
$ Lineseparator = "\ n";
/ / Kode ini membaca file tatami ke dalam database
$ Con = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) or die (mysql_error ());
@ Mysql_select_db ($ databasename) or die (mysql_error ());
/ / Ini loops selama beberapa file
for ($ r = 2; r $ <14; $ r + +) {
for ($ c = $ r; $ c
Berikut ini melakukan trik untuk saya:
LOAD DATA LOCAL INFILE LOW_PRIORITY
'C: \ \ Documents and Settings \ \ Administrator \ \ Desktop \ \ SigmaS1.csv'
INTO TABLE `` `mydb mytable.`
BIDANG melarikan diri dengan '\ \'
DIHENTIKAN OLEH ','
Opsional tertutup oleh '"'
LINES DIHENTIKAN OLEH '\ r \ n'
(`User`, `pwd`, `SnO`, `AMT`, `ActiveRec`);
Script ini membaca sebuah baris tambahan dari file csv. misalnya jika file csv memiliki 25 catatan Hal ini menunjukkan ada 26 catatan. Bisakah anda jelaskan kemana aku pergi salah?
Saya telah menambahkan untuk memeriksa apakah itu adalah baris pertama dan melanjutkan loop jika baris pertama.
terima kasih
Seperti Gary, aku ingin bisa menimpa data yang sudah ada, tetapi dengan memperbarui itu, tidak menghapus seluruh data di db. Sp suatu tempat di sekitar sini:
if ($ addauto)
$ Query = "insert into nilai $ databasetable (",'$');"; linemysql
lain
$ Query insert = "ke nilai databasetable $ ('$ linemysql');";
Bagaimana cara memeriksa untuk melihat apakah mencatat ada dan kemudian Update daripada Sisipkan?
Bagaimana cara melompati baris pertama / baris yang merupakan header di file csv dan masukkan sisa data ke db?
@ Gary
Anda bisa menggunakan @ mysql_query ("truncate $ databasetable"); tepat setelah pernyataan mysql_select_db @.
Tapi hati-hati karena tindakan ini akan menghapus data dan tidak reversibel.
@ Kish
kode saat ini tidak memungkinkan untuk browsing / upload file.
Anda cukup menempatkan file CSV dalam direktori yang sama seperti naskah PHP, dan hanya menyetel variabel $ csvfile akan sama dengan nama file (tanpa path)
Hi semua,
Bagaimana saya mengandung csv kutipan pada tanggal "hari, tanggal, bulan, 2010" dan negara "prov, negara" ke kolom dalam basis data saya? Saya melihat banyak contoh tetapi saya tidak bisa mendapatkannya bekerja. bantuan akan baik.
ak, 10037591,1, "Selasa, 9 Mar 2010 15:55:16", 59,7151, -151.4434,2.7,75.90,32, "Semenanjung Kenai, Alaska"
thx
Terima kasih, kode ini telah benar-benar membantu!
Bagaimana aku memodifikasi untuk memungkinkan formulir untuk ditampilkan di mana pengguna menelusuri dan memilih file csv yang akan diimpor ke dalam tabel?
Dan juga bagaimana aku bisa membuatnya sehingga setiap kali file yang baru diajukan itu akan menimpa apa pun yang tersimpan saat ini dalam tabel?
Banyak terima kasih
Kode ini sangat berguna bagi saya ..
terima kasih.
Bagaimana saya bisa mendapatkan browse file bukan mengetik nama path lengkap ..
Tolong bantu dalam hal ini.
terima kasih
saya tidak mengerti bagaimana bekerja dari control file. berarti pertama menelusuri dan memilih file dan kemudian mengirimkan mana saya perlu diubah
Halo,
Membuat beberapa modifikasi. . File txt saya memiliki 3 kolom dipisahkan oleh | karakter (pipa) "". Script menampilkan file data, jumlah baris, tetapi tidak memasukkan data ke dalam database. Ada komentar?
$ Csvcontent = fread ($ file, $ ukuran);
fclose ($ file);
$ Con = @ mysql_connect ($ dbhost, $ dbusername, $ dbuserpassword) or die (mysql_error ());
@ Mysql_select_db ($ sumber data) atau mati (mysql_error ());
$ Lineseparator = "\ n";
$ Fieldseparator = "|";
$ Baris = 0;
$ Query = "";
$ Linearray = array ();
$ Count = 0;
foreach (split ($ lineseparator, $ csvcontent) sebagai $ baris) {
$ Count = $ count + 1;
$ Baris + +;
$ Baris = trim ($ line, "\ t");
$ Baris = str_replace ("\ r ","",$ baris);
/************************************
Baris ini lolos karakter khusus. menghapusnya jika entri sudah lolos dalam file csv
************************************/
$ Baris = str_replace ("'"," \ '", $ baris);
/*************************************/
$ Linearray = meledak ($ fieldseparator, $ line);
$ Linemysql = meledak linearray (""",$);
if ($ addauto)
$ Query = "insert into nilai INDIKATOR ('$ count', '$ linemysql');";
lain
$ Query = "insert into nilai INDIKATOR ('$ linemysql');";
$ Query $ query .=. "\ N";
@ Mysql_query ($ query) or die (mysql_error ());
echo "$ linemysql \ n";
}
Excellent script! Saya butuh mulai melompat kecil untuk sebuah proyek saya bekerja dan ini melakukan trick.
Saya melakukan sesuatu yang aneh melihat Namun, saya memodifikasi script untuk bekerja dengan membentuk dan saya melihat bahwa untuk mencari, field terakhir semakin kabur karena sama dengan baris baru char (baik \ r atau \ n atau keduanya) masih sedang direkam dalam database MySQL.
Untuk itu, jika Anda mengganti:
$ Baris = str_replace ("\ r ","",$ baris);
dengan:
$ Baris = str_replace ('\ r',",$ baris);
itu akan terus kembali dari menjadi masalah, karena untuk baris baru, saya telah menambahkan sedikit sesuatu yang memungkinkan untuk memasukkan catatan baru, tapi update yang ada catatan, sehingga Anda tidak berakhir dengan entri duplikat. Di bagian atas kode di bawah, Anda akan melihat di mana saya membuat memperbaiki yang sama untuk baris baru sebenarnya char.
$ Linemysql = meledak linearray ("','",$);
$ Newlinemysql = str_replace ('\ n linemysql',",$);
if ($ addauto) {
switch ($ databasetable) {
kasus ('address'):
$ Duplicatevals = "alamat = VALUES (alamat),
kota = NILAI (kota), negara = NILAI (negara),
zip = NILAI (zip) ";
break;
kasus ('pemilik'):
$ Duplicatevals = "ownername = VALUES (ownername),
housetype = NILAI (housetype),
addresskey = NILAI (addresskey) ";
break;
}
$ Query = "insert into nilai databasetable $ newlinemysql (",'$ ')
SALINAN TENTANG UPDATE KUNCI
$ Duplicatevals ";
} Else {
$ Query = "insert into $ databasetable nilai ('$ linemysql')
SALINAN TENTANG UPDATE KUNCI
$ Duplicatevals ";
}
Juga, dalam bentuk saya menambahkan nama tabel dan apakah aku ingin tabel yang akan [boolean] "addauto" atau bukan sebagai masukan tunggal dari-drop-down (dipisahkan koma), kemudian membelah hasilnya di bagian atas simplecsvimport yang script.
Akhirnya, Anda harus ingat untuk mengatur indeks dalam database untuk, "ON SALINAN ..." untuk bekerja, kenaikan otomatis tidak akan bekerja dalam kasus ini, jadi anda harus menetapkan indeks sekunder di atas meja otomatis kenaikan, tabel yang don t auto 'kenaikan dan memiliki ladang yang unik bekerja dengan indeks tunggal jika itu adalah rute Anda ingin pergi.
Saya harap ini membantu seseorang!
Cheers!
I need to download data automatically from a remote server. Its a CSV file, and i need to unzip it, and store the data in a mysql database that i created. There are multiple databases. The first section below is one of the databases that someone helped me with and it works wonderfully. I set up a cron job and it downloads it automatically as scheduled. However i have more databases and cant get the others to work.
THIS SECTION BELOW WORKS FINE!!!!
—————————————————————————–
# /! Bin / bash
deleteparam='–delete-after';
#deleteparam=”
#directory='–directory-prefix=/$HOME/myfolder/myfolder/'
directory=”
#userpwd='–http-user=blah –http-password=blah'
toUpper() {
echo $1 | tr “[:lower:]” “[:upper:]”
}
#if [ -z "$1" ]; then
# echo usage: $0 table
#exit
#fi
ZIP=name of data file in remote server
ZIP=`toUpper $ZIP`
#the file within the zip has one less _
DATA=name of table in my mysql database
DATA=`toUpper $DATA`
#rm $TABLE.csv.zip
#rm $DATA.csv
cd /$HOME/myfolder/myfolder/
#######get the residential
wget ' https://3pv.mlslirealtor.com/Data3pv/DownloadBRSaction.asp?user_code=XXXXXX&password=XXXXXXX&data_type=datazip ' -O $ZIP.csv.zip
sleep 10
#######unzip it
pwd
ls -la
unzip -o $ZIP.csv.zip
sleep 10
#######load it
wget –verbose $deleteparam $directory $userpwd https://mywebsite/myfolder/import.php?table=$DATA
sleep 300
######delete the files
rm $ZIP.csv.zip
rm $DATA.csv
sleep 10
_———————————————————————————
ALL OF THIS ABOVE WORKS WONDERFUL
THIS IS WHAT I NEED HELP WITH
—————————————————————————-
1. I need a script to add to the above file that will download the photos. If you see below i need a script that automatically gets the CURRENT date and time that the script is ran. There server holds pic from the last 7 days and is constantly updated. Once this script is ran it will download the data into the table that i created.
2. Then, I need a script that queries the mysql database looking for entries that have photos and then retrieve the actual photos directly from their remote servers. This csv file DOES NOT download photos, just data that i can use to run a script to retrieve the photos at a given spot. Lihat di bawah.
Below are the instructions I received.
INSTRUKSI
Photo data is retrieved by HTTP. The photos data is updated once daily and is available for download as a CSV file. You can then write a script using the data from the CSV file to point back to the images on our image server. YOU MUST SUPPLY A VALUE FOR THE QUERY STRING last_updt > 'YYYYMMDD HH:MM:SS' for the URL to return data. The field last_updt is the date value for the last time that a photo was changed on the listing.
You will need to replace the user_code and password place holders (XXXX) with the login credentials provided to you.
Step 1: To retrieve the primary listing photo data CSV file go to the URL below.
https://remotewebserver/Data3pv/DownloadBRSaction.asp?user_code=XXX&password=XXXX&query_str=last_updt%20>%20'YYYYMMDD%20HH:MM:SS'&data_type=PHOTOS
Step 2: The photos table data should download in a CSV format.
Step 3: Using the Y flags and the ML Number in the data you can link back to our image locations.
Our primary image directory path is as follows:
https://remoteserver/folder/folder/folder/Last3DigistsofML#/listing#.jpg
For example- The primary photo for listing number 1899430 is located at
https://remoteserver/folder/folder/1/430/1899430.jpg
Our additional image directory path structure is as follows:
https://remoteserver/mlsphotos/full/PhotoPosition/Last3DigistsofML#/listing#_photoPosition.jpg
For example- The second photo for listing number 1899430 is located at
https://remoteserver/folder/folder/2/430/1899430_2.jpg
Hi, it tells me the record count but not putting data into database
Hope you can help
Nathan
the command is: truncate tablename.
you can insert the following on line 58:
@mysql_query(“truncate $databasetable”);
but this is non reversible! so be careful
how can i empty my already filled table before inserting the new file?
or can i update an already existing input?
TRUNCATE, UPDATE? how do i get this in the query?
@Andy Brotherton : This means that the query is attempting to insert a record with a number of columns that do not match that of the database table.
1) Are you sure that the CSV file has the exact same number of columns as the table in the database?
2) Is the field separator in this CSV file really a comma? or is it a tab for instance or other? If it's not a comma, change the value of $fieldseparator on line 12
3) The table need to be already created in the database before attempting to load data into it. Are you sure you have it?
Halo,
I would really like to use this script but I'm not sure what I am doing wrong. I get the same problem mentioned above with data not loading into the db. It finds the correct number of rows but nothing shows in the db.
I changed line 88 @mysql_query($query) or die(mysql_error());
and get this message “Column count doesn't match value count at row 1″
@Claus
Hello Claus.
Does the CSV really contain a single record?
Since the script reached the stage where it outputs the number of records, I assume it didn't fail when it connected to the database (lines 56-57) so that is not the problem.
It is possible that the query to insert data is failing.
Try replacing line 88 with:
mysql_query($query) or die(mysql_error());
and check what error you get.
@Okoth
Hello Okoth.
Most likely, you can get rid of lines 33-54 and replace them with this single line:
$csvcontent = @file_get_contents("https://. . .");
replace the dots with the appropriate url (direct url to the CSV file)
@Adrian
Hello Adrian.
Drupal, as you noted, has complex table structures. Depending on what sort of data you are importing, it's very likely that this data needs to be split into multiple tables, usually with a common foreign key such as the node id.
Unfortunately, the script above wouldn't help do that.
Terima kasih untuk script. Very understandable.
How can I modify this script so that it fetches and store a csv file from the Internet into MySQL?
Hi All
I am using drupal to build a new website, the challenge I am having right now is that I need to import data from a CSV file into a mysql database which has shared tables, therefore some of the fields into which I need to import csv data are in different sections of the same database will this script work for me? If not can this csv file be imported using another method?
Please advise, thank you for any assistance.
Salam
Adrian
Hi everyone!
Seem to have the script working…exept that it does not write data to the mysql…
Like with Chris: The script completes, and even outputs the record count, but doesn't touch the database at all… but tells me: Found a total of 1 records in this csv file.
What do I do wrong (im a noob at php and mysql)
Terima kasih
Claus
Hi Stanley, the problem is with the single quotes. The blog software here rewrites them. Simply replace ' and ' with '
PS: the command above is to directly load a csv file into the database from the mysql prompt. This is nice but not related to the script above
it says to load this into the data base
load data local infile 'PATH' into table TABLE fields terminated by ',' lines terminated by '\n';
i change the path and the table its going into but it gives me an error that its the wrong syntax code 1064
can anyone give me some advise on what to do
terima kasih
stan
With regards to the quotes issue, you can just use this:
$linearray = preg_split(“/,(?=(?:[^\"]*\”[^\"]*\”)*(?![^\"]*\”))/”, $line);
Cheers,
Gaz.
Dear Chris,
please replace:
@ Mysql_query ($ query);
dengan:
@mysql_query($query) or die(mysql_error());
and let me know what error it gives you
Hei Semua orang,
Love this script, and it was working fine, now suddenly the script wont insert the records. The script completes, and even outputs the record count, but doesn't touch the database at all…
Ada gagasan?
Terima kasih
C
Hi Mark,
first, it's referring to the file you selected in the $outputfile variable.
second, this file needs to be writable. I assume you're using Linux, not windows, as this is generally not an issue with windows.
On linux, simply SSH to the machine, change to the directory where the output file is, and type: chmod 777 filename
where 'filename' is the actual file name.
If you don't have SSH, many FTP clients support permission change. For this purpose, FTP to the folder containing the output file, then select this file, and locate from this ftp software the option to change permission. Set it to 777, or 'read, write, execute' for everyone.
Hi semua,
Terima kasih untuk script. I'ma noob at PHP and MySQL so I really appreciate something like this. I got as far as generating the “File is not writable, check permissions” error message in my browser. Can someone please explain the comment about setting the permission to 777? I'm using an Excel-generated .csv file? Thanks in advance.
I can only get the first line of my CSV file to be imported into the database.
Here's a copy of the log file:
insert into production values(”,'2008-10-21′,'50′,'50′,'50′,'this is the first notes line','this is notes line 2′,'this is notes line 3′,'0000-00-00′,'0000-00-00′,'0000-00-00′,'456 Morningside Ave','ste. 512′,'Brooklyn','NY','10023′,'Joe','Customer 1′);
insert into production values(”,'2008-10-09′,'50′,'50′,'50′,'this is the first notes line',”,”,'2008-10-09′,'2008-10-14′,'0000-00-00′,'456 Morningside Ave','ste. 512′,'Brooklyn','NY','10023′,'Joe','Customer 1′);
insert into production values(”,'2008-10-14′,'25′,'25′,'25′,'NOTES 1′,”,”,'2008-10-14′,'2008-10-17′,'NULL','555 somewhere','suite 123′,'new york','new y','10001′,'Joe','Name 1′);
insert into production values(”,'2008-10-16′,'45′,'45′,'45′,”,”,”,'2008-10-16′,'2008-10-24′,'NULL',”,”,”,”,”,'Tom',”);
insert into production values(”,'2008-10-01′,'34′,'34′,'34′,”,”,”,'2008-10-02′,'2008-10-04′,'2008-10-04′,”,”,”,”,”,'Steve',”);
insert into production values(”,'2008-10-17′,'50′,'50′,'50′,'this is the first notes line',”,”,'2008-10-03′,'0000-00-00′,'0000-00-00′,'456 Morningside Ave','ste. 512′,'Brooklyn','NY','10023′,'Joe','Customer 1′);
insert into production values(”,'2008-10-18′,'25′,'25′,'25′,'NOTES 1′,”,”,'2008-10-04′,'0000-00-00′,'0000-00-00′,'555 somewhere','suite 123′,'new york','new y','10001′,'Joe','Name 1′);
insert into production values(”,'2008-10-19′,'45′,'45′,'45′,”,”,”,'2008-10-05′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,'Tom',”);
insert into production values(”,'2008-10-20′,'34′,'34′,'34′,'new notes',”,”,'2008-10-06′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,'Steve',”);
insert into production values(”,'2008-10-21′,'12′,'12′,'12′,'even newer notes',”,”,'2008-10-07′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,'mark',”);
insert into production values(”,'2008-10-22′,'1′,'0′,'0′,”,”,”,'2008-10-08′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”,”);
insert into production values(”,'2008-10-23′,'2′,'0′,'0′,”,”,”,'2008-10-09′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”,”);
insert into production values(”,'2008-10-24′,'3′,'0′,'0′,”,”,”,'2008-10-10′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”,”);
insert into production values(”,'2008-10-15′,'0′,'0′,'0′,'later',”,”,'2008-10-11′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”,”);
insert into production values(”,'2008-10-16′,'0′,'0′,'0′,'later still',”,”,'2008-10-12′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”,”);
insert into production values(”,'2008-10-17′,'0′,'0′,'0′,'later still',”,”,'2008-10-13′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”);
insert into production values(”,'2008-10-18′,'0′,'0′,'0′,'later still',”,”,'2008-10-14′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”);
insert into production values(”,'2008-10-19′,'0′,'0′,'0′,'latest',”,”,'0000-00-00′,'0000-00-00′,'0000-00-00′,”,”,”,”,”,”);
insert into production values(”,'2008-10-01′,'34′,'34′,'34′,'very latest',”,”,'2008-10-02′,'2008-10-04′,'2008-10-04′,”,”,”,”,”,'bruce');
insert into production values(”,”);
It says it's inserting 20 records, but only the first one makes it into the database. Any thoughts?
it did not insert into the database table where i want it inserted..:(
Nice work chief
Hi semua,
I made a minor change to your code, so it works as a CSV importer, as it should.
CSV-s first line should hold the COLUMN NAMEs you want to import, so change the FOREACH loop:
foreach(split($lineseparator,$csvcontent) as $line) {
$ Baris + +;
$line = trim($line,” \t”);
$line = str_replace(“\r”,”",$line);
/*get COLUMN NAMEs from first line of CSV */
if($lines==1) {
$columns=explode($fieldseparator,$line);
$columnsql=implode(“,”,$columns);
echo $columnsql;
continue;
}
/************************************
Baris ini lolos karakter khusus. menghapusnya jika entri sudah lolos dalam file csv
************************************/
$line = str_replace(“'”,”\'”,$line);
/*************************************/
$ Linearray = meledak ($ fieldseparator, $ line);
$linemysql = implode(“','”,$linearray);
if($addauto)
$query = “insert into $databasetable ($columnsql) values('$linemysql');”;
lain
$query = “insert into $databasetable ($columnsql) values('$linemysql');”;
$queries .= $query . “\n”;
@ Mysql_query ($ query);
}
How large is the file you're trying to import?
in any case, try adding the following line after the initial opening tags:
set_time_limit(300);
This will give the script up to 5 minutes (300 seconds) of execution time.
Replacing 300 with 0 will allow it to take as much time as needed.
Hi there, nice script thanks. When running it I get:
Fatal error: Maximum execution time of 30 seconds exceeded in on line 63
Is there anything I can do to get around this?
Robbie, thanks for you addition, it's quite welcome. Unfortunately, it doesn't work straight away when I copy it. I think something is missing because the code is spread out over two posts.
Could you check the code as displayed here? Is something missing?
brad, if you had downloaded it earlier than last week, replace the '< ?'at the top with '< ?php' (remove space)
i get the first so much of it cut off and the rest just code in my browser. I know php is working because the rest of the site works.
I did upgrade to php5 does that matter?
)
; // skip because it falls within the bad array elements
lain
$newarray[$y] = str_replace('”',”,$linearray[$y]);
$linearray = array_values($newarray); // reset the keys to the new array
$x++;
}
}
}
Well, here's the fix to my previous comment:
insert this in between:
$ Linearray = meledak ($ fieldseparator, $ line);
… insert code snippet below….
$linemysql = implode(“','”,$linearray);
Finds and keeps all “Stuff, More Stuff” together before imploding it.
$a = “”;
$b = “”;
$qoutecount = 0;
for ($x = 0; $x -1) {
$qoutecount++;
if ($qoutecount == 1)
$a = $x; // store the first instance
elseif ($qoutecount == 2) {
$quotecount = 0;
$b = $x; // store the second instance
// THAT DOES IT… compile all elements from $a to $b into $a and ignore elements anything after $a to $b in new array;
$newa = “”; // initialize new string.
for ($z = $a; $z $a && $y
Doesn't account for fields such as this line:
Fname, Lname, “Company, Inc”, City, State, Zip
Company and Inc get split into two different columns.
Rengaraj,
the csv file should be in the same place as the PHP file.
Also, you don't really have to use the same csv file name.
bbqrest.csv is an example, replace this file name with your own.
Can any one reply fast i have a csv file bbqrest.csv at correct path(root)..
I am getting this error File not found. Make sure you specified the correct path.
it would be a good idea to add prevent headers within the csv from being submitted into the database. Or to create a script that pulls out the first row and creates a db using these values as the column names.
Steve,
You would place this script into a web-accessible folder, after changing the variables that need to be changed. Read the comments in the script to find out what you need to specify. Then, call the script up in a web browser, like:
https://www.example.com/path-to-script/simplescvimport.php
Total newbie – tearing my hair out trying to import Excel csv into phpMyAdmin (on a Mac). Would love to know exactly where and what I do with this php script…?
Wow is cool … had idea after read your coding… thank a lot
Hi there, a small modification for auto incrementing values in column 1 (id field)
see variable $count.
ola, enrico.
//$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
//@mysql_select_db($databasename) or die(mysql_error());
$ Baris = 0;
$ Query = "";
$linearray = array();
$count = 0;
foreach(split($lineseparator,$csvcontent) as $line) {
$count = $count + 1;
$ Baris + +;
$line = trim($line,”\t”);
$line = str_replace(“'”,”\'”,$line);
$ Linearray = meledak ($ fieldseparator, $ line);
$linemysql = implode(“','”,$linearray);
$query = “insert into `your db table` VALUES('$count','$linemysql');”;
$queries .= $query . “\n”;
@ Mysql_query ($ query);
}
//@mysql_close($con);
Thanks a lot this saved lots of time! Nice script.
I usually use phpmyadmin, but true, in case one does not have it installed, and does not have shell access (like most of the shared hosting providers), this can come in very handy.
Very useful, thank you.