PHP-скрипт для імпорту CSV даних в MySQL
Це простий скрипт, який дозволить вам імпортувати CSV-даних в базі даних. Це попадеться під руку, тому що ви можете просто відредагувати відповідні поля, завантажити його разом з CSV-файл і назвіть його з Інтернету, і він буде робити все інше.
Це дозволяє вказати роздільник в цьому файлі CSV, чи є це кому, вкладки і т.д. Вона також дозволяє вам вибрати лінію сепаратора, дозволяє зберегти висновок у файл (так званий дамп даних SQL).
Це також дозволяє вам включати пусте поле на початку кожного рядка, яка, як правило, цілими автоматичне збільшення первинного ключа.
Цей сценарій корисний головним чином, якщо у вас немає PhpMyAdmin, або ви не хочете клопоту входу в систему і вважають за краще кілька кліків рішення, або ви просто командний рядок хлопець.
Просто переконайтеся, що таблиця вже створена, перш ніж намагатися скинути дані.
Будь ласка, ваші коментарі, якщо ви отримали будь-якої звіт про помилку.

Дуже корисно, дякую.
Я зазвичай використовую PhpMyAdmin, але правда, у разі не повинна бути встановлена, і не має доступу до командного оболонці (як і більшість хостинг-провайдерів), це може виявитися дуже до речі.
Велике спасибі це врятувало багато часу! Ніцца сценарій.
[...] Що ж, сьогодні я хочу представити вам ще один метод отримання Вашого CSV файл в SQL, використовуючи PHP коду. За цей шматок коду, повний кредит йде на легенду. Ви повинні переконатися, що база даних вже створена, перш ніж скинути дату. /************************************************* *******************************************/ / * Код на HTTP: / / legend.ws / блог / поради-трику / CSV-PHP-MySQL-імпорт / / * Змінити записи нижче, щоб відображати відповідні значення /****************** ************************************************** ************************/ $ databasehost = "локальний"; $ DatabaseName = "тест", $ databasetable = "зразок", $ databaseusername = " тест "; $ databasepassword =" "; $ fieldseparator =" "; $ LineSeparator =" п "; $ csvfile =" bbqrest.csv "; /***************** ************************************************** *************************/ / * Хочете додати ampty поле на початку цих записів? / * Це корисно, якщо у вас є таблиця з першого поля auto_increment бути ціле число / * і CSV-файл не має таких як порожні поля перед записами. / * Установка 1 для так, і 0 якщо немає. УВАГА: не встановлено в 1, якщо ви не впевнені. / * Це може скинути дані в неправильних полях, якщо це додаткове поле не існує в таблиці /***************************** ************************************************** *************/ $ addauto = 0; /****************************** ************************************************** ************/ / * Ви хочете зберегти MySQL запитів в файл? Якщо так безліч $ економити до 1. / * Дозвіл на файл повинен бути встановлений в 777. Або завантажити зразок файлу через FTP і / * зміна дозволів, або виконувати в командному рядку: сенсорний output.sql & & CHMOD 777 output.sql /******************* ************************************************** ***********************/ $ економити = 1; $ вихідний_файл = "output.sql"; /*********** ************************************************** *******************************/ [...]
Привіт там, невелика модифікація для автоматичного збільшення значення у стовпці 1 (ідентифікатор поля)
см. змінну $ в рахунок.
ола, Енріко.
/ / $ Кон = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) або померти (mysql_error ());
/ / @ Mysql_select_db ($ DatabaseName) або померти (mysql_error ());
$ Прямих = 0;
$ Запитів = "";
$ Linearray = Array ();
$ Count = 0;
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$ Count = $ Count + 1;
$ Прямих + +;
$ = Лінія обробки ($ рядок, "\ т");
$ Рядок = str_replace ("'"," \ '", $ рядок);
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
$ Linemysql = вибухати ("','",$ linearray);
$ Запит = "вставити` ваша база таблиці `VALUES ('$ підрахунок', '$ linemysql');";
$ Запитів .= $ запиту. "\ П";
@ Mysql_query ($ запиту);
}
/ / @ Mysql_close ($ CON);
[...] На подібної ноті, ось готовий скрипт, який його автор каже, буде імпортувати файл CSV в MySql: PHP скрипт для імпорту CSV даних в MySQL. [...]
[...] /******************************************** ************************************************/ / * Код на http://legend.ws/blog/tips-tricks/csv-php-mysql-import/ / * Змінити записи нижче, щоб відображати відповідні значення /************* ************************************************** *****************************/ $ databasehost = "локальний"; $ DatabaseName = "ххххх", $ databasetable = "XXXX" ; $ databaseusername = "XXXX", $ databasepassword = "XXXX", $ fieldseparator = ""; $ LineSeparator = "п"; $ csvfile = "xport/2008_BF.csv"; /********* ************************************************** *********************************/ / * Хочете додати ampty поле на початку цих записів ? / * Це корисно, якщо у вас є таблиця з першого поля auto_increment бути ціле число / * і CSV-файл не має таких як порожні поля перед записами. / * Установка 1 для так, і 0 якщо немає. УВАГА: не встановлено в 1, якщо ви не впевнені. / * Це може скинути дані в неправильних полях, якщо це додаткове поле не існує в таблиці /***************************** ************************************************** *************/ $ addauto = 0; /****************************** ************************************************** ************/ / * Ви хочете зберегти MySQL запитів в файл? Якщо так безліч $ економити до 1. / * Дозвіл на файл повинен бути встановлений в 777. Або завантажити зразок файлу через FTP і / * зміна дозволів, або виконувати в командному рядку: сенсорний output.sql & & CHMOD 777 output.sql /******************* ************************************************** ***********************/ $ економити = 1; $ вихідний_файл = "output.sql"; /*********** ************************************************** *******************************/ [...]
Wow прохолодно ... виникла ідея після читання вашого кодування ... Дякую багато
Усього новачка - рву на собі волосся, намагаючись імпортувати в Excel CSV PhpMyAdmin (на Mac). Дуже хотілося б точно знати, де і що мені робити з цим сценарієм PHP ...?
Стів,
Ви б помістити цей скрипт в веб-папку доступною, після заміни змінних, які повинні бути змінені. Читайте коментарі в сценарій, щоб дізнатися, що вам потрібно вказати. Потім, виклик сценарію у веб-браузер, наприклад:
http://www.example.com/path-to-script/simplescvimport.php
було б непогано додати запобігти заголовки в CSV від представлених в базі даних. Або створити скрипт, який витягує першого рядка і створює БД за допомогою цих значень, імена стовпців.
Я отримую цю помилку Файл не знайдений. Переконайтеся, що ви вказали правильний шлях.
Чи може одна відповідь швидко у мене є bbqrest.csv CSV файл на правильний шлях (кореневої) ..
Rengaraj,
CSV-файл повинен бути в тому ж місці, що й файл PHP.
Крім того, ви дійсно не повинні використовувати той же файл CSV ім'я.
bbqrest.csv є, наприклад, замінити це ім'я файлу з вашим власним.
Не враховує таких областях, як цей рядок:
Fname, Lname ", компанія, Inc", місто, штат, поштовий індекс
Компанії та одержати Inc розділити на дві різні стовпці.
Ну, от виправити на мій попередній коментар:
вставити це між ними:
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
... Вставити фрагмент коду нижче ....
$ Linemysql = вибухати ("','",$ linearray);
Знаходить і зберігає всі "Stuff, більше матеріалу" вибухає разом перед нею.
$ = "";
$ Ь = "";
$ Qoutecount = 0;
для ($ х = 0; $ х -1) {
$ Qoutecount + +;
якщо ($ qoutecount == 1)
$ = $ Х; / / зберігаємо першої інстанції
ElseIf ($ qoutecount == 2) {
$ Quotecount = 0;
$ Ь = $ х; / / зберігаємо другої інстанції
/ / ЩО ЦЕ ... зібрати всі елементи від $ до $ в $ б і ігнорувати елементи що-небудь після $ до $ б в новий масив;
Нева $ = ""; / / инициализируем новий рядок.
для (г = $ $, $ Z $ & & $ у
)
/ / Підтвердити, оскільки вона входить в поганих елементів масиву
ще
$ Newarray [$ у] = str_replace ('"',",$ linearray [$ у]);
$ Linearray = array_values ($ newarray) / / скидання ключів в новий масив
$ Х + +;
}
}
}
я отримати першу в тій частині, відрізати, а інші просто код в моєму браузері. Я знаю, PHP працює, тому що решта сайт працює.
Я зробив оновлення до php5 це має значення?
Бред, якби ти скачав його раніше, ніж минулого тижня, замінити "<?" У верхній з "<? PHP" (убрать пробіл)
Роббі, спасибі, що ви того, це дуже вітається. На жаль, це не відразу, коли я його копіювання. Я думаю, що чогось бракує, так як код поширюється протягом двох посад.
Не могли б ви перевірити код, як показано тут? Что-то не вистачає?
Привіт там, завдяки гарним сценарієм. При запуску цього я отримую:
Фатальна помилка: Максимальний час виконання 30 секунд перевищено у рядку 63
Є все, що я можу зробити, щоб обійти це?
Наскільки великий файл, який ви намагаєтеся імпортувати?
У будь-якому випадку, спробуйте додати наступний рядок після початкового відкриття теги:
set_time_limit (300);
Це дасть сценарію до 5 хвилин (300 секунд) часу виконання.
Заміна 300 з 0 дозволить їй зайняти стільки часу, скільки необхідно.
Привіт всім,
Я зробив невеликі зміни в коді, так що він працює як імпортер CSV, як слід.
CSV-х років перша лінія повинна тримати імена стовпців, які потрібно імпортувати, так що зміна цикл по кожному елементу:
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$ Прямих + +;
$ = Лінія обробки ($ рядок, "\ т");
$ Рядок = str_replace ("\ г ","",$ лінія);
/ * Отримати імена стовпців з першої рядку CSV * /
якщо ($ прямих == 1) {
$ = Вибухнути стовпців ($ fieldseparator, $ рядок);
$ Columnsql = вибухати (",",$ колони);
Відлуння $ columnsql;
продовжуватися;
}
/************************************
Ця лінія втечу особливий характер. видалити його, якщо записи вже біг в файл CSV
************************************/
$ Рядок = str_replace ("'"," \ '", $ рядок);
/*************************************/
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
$ Linemysql = вибухати ("','",$ linearray);
якщо ($ addauto)
$ Запит = "вкласти в $ databasetable ($ columnsql) значення ('$ linemysql');";
ще
$ Запит = "вкласти в $ databasetable ($ columnsql) значення ('$ linemysql');";
$ Запитів .= $ запиту. "\ П";
@ Mysql_query ($ запиту);
}
Ніцца головна праця
це не вкласти в таблицю бази даних, де я хочу це вставлено ..: (
Я можу отримати тільки перший рядок мого CSV-файл для імпорту в базу даних.
Ось копія файлу журналу:
вкласти в виробництві цінностей (", '2008-10-21 ', '50', '50 ', '50', 'це перша лінія відзначає", "це відзначає рядку 2", "це зазначає, лінія 3 ', '0000-00-00', '0000-00-00 ', '0000-00-00', '456 Morningside проспект ',' Ste. 512 »,« Бруклін »,« Нью-Йорк ', '10023', «Джо», «Клієнт 1 ');
вкласти в виробництві цінностей (", '2008-10-09 ', '50', '50 ', '50', 'це перша лінія відзначає',",",' 2008-10-09', '2008 -10-14 ', '0000-00-00', '456 Morningside проспект »,« Сент-512 »,« Бруклін »,« Нью-Йорк ', '10023', 'Джо', 'Клієнт 1').
вкласти в виробництві цінностей (", '2008-10-14 ', '25', '25 ', '25', 'ПРИМІТКИ 1',",",' 2008-10-14', '2008-10-17 ',' NULL ', '555 десь', 'пакет 123 »,« Нью-Йорк "," новий у', '10001 ',' Джо ',' Ім'я 1 ');
вкласти у виробництво
вкласти у виробництво
вкласти в виробництві цінностей (", '2008-10-17 ', '50', '50 ', '50', 'це перша лінія відзначає',",",' 2008-10-03', '0000 -00-00 ', '0000-00-00', '456 Morningside проспект »,« Сент-512 »,« Бруклін »,« Нью-Йорк ', '10023', 'Джо', 'Клієнт 1').
вкласти в виробництві цінностей (", '2008-10-18 ', '25', '25 ', '25', 'ПРИМІТКИ 1',",",' 2008-10-04', '0000-00-00 ', '0000-00-00', '555 десь ',' пакет 123 »,« Нью-Йорк "," новий у ', '10001', 'Джо', 'Ім'я 1');
вкласти у виробництво
вкласти в виробництві цінностей (", '2008-10-20 ', '34', '34 ', '34', 'нові ноти',",",' 2008-10-06', '0000-00-00 ', '0000-00-00',",",",",",' Стів',");
вкласти в виробництві цінностей (", '2008-10-21 ', '12', '12 ', '12', 'навіть новіше відзначає',",",' 2008-10-07', '0000-00- 00 ', '0000-00-00',",",",",",' знак',");
вкласти у виробництво
вкласти у виробництво
вкласти у виробництво
вкласти у виробництво
вкласти в виробництві цінностей (", '2008-10-16 ', '0', '0 ', '0', 'ще пізніше',",",' 2008-10-12', '0000-00-00 ', '0000-00-00',",",",",",",");
вкласти в виробництві цінностей (", '2008-10-17 ', '0', '0 ', '0', 'ще пізніше',",",' 2008-10-13', '0000-00-00 ', '0000-00-00',",",",",",");
вкласти в виробництві цінностей (", '2008-10-18 ', '0', '0 ', '0', 'ще пізніше',",",' 2008-10-14', '0000-00-00 ', '0000-00-00',",",",",",");
вкласти у виробництво
вкласти в виробництві цінностей (", '2008-10-01 ', '34', '34 ', '34', 'найостаннішу',",",' 2008-10-02', '2008-10-04 ', '2008-10-04',",",",",",' Брюс');
вкласти у виробництво значення (",");
Він каже, що це вставка 20 записів, але тільки перший з них робить його в базу даних. Які-небудь думки?
Привіт всім,
Дякуємо за сценарій. Я нуб на PHP і MySQL, так що я дуже ціную те зразок цього. Я добрався до генерації "Файл не доступний для запису, перевірте права" повідомлення про помилку в браузері. Може хтось будь ласка, поясніть коментар про налаштування дозвіл 777? Я використовую Excel-породжений. CSV-файлу? Спасибо заранее.
Привіт Марко,
по-перше, то маються на увазі вибраний файл $ вихідний_файл змінної.
по-друге, цей файл має бути доступний для запису. Я припускаю, ви використовуєте Linux, а не вікна, як це зазвичай не проблема з вікнами.
У Linux просто SSH до машини, перейдіть в каталог, де вихідний файл, і введіть: CHMOD 777 файлу
де "ім'я файлу" є фактичне ім'я файлу.
Якщо у вас немає SSH, FTP, багато клієнтів підтримують дозвіл зміниться. Для цієї мети, FTP до папки, яка містить вихідного файлу, а потім виберіть цей файл і знайдіть з цього FTP програмне забезпечення можливість зміни дозволу. Встановіть його на 777, або "читання, запис, виконання для всіх.
Привіт всім,
Любите цей сценарій, і він працює нормально, тепер раптом сценарій звичай вставляти записи. Сценарій завершується, і навіть виходи кількість записів, але не чіпає базу даних на всі ...
Будь-які ідеї?
Спасибі
C
Дорогий Кріс,
будь ласка, замініть:
@ Mysql_query ($ запиту);
з:
@ Mysql_query ($ запиту) або померти (mysql_error ());
і дайте мені знати, яку помилку він надає
Що стосується питання лапки, ви можете просто використовувати це:
$ Linearray = preg_split ("/,(?=(?:[^ \ "] * \" [^ \ "] * \ ")*(?![^ \"] * \ $ "))/", лінії );
Cheers,
Газ.
він каже, щоб завантажити це в базу даних
LOAD DATA LOCAL INFILE 'PATH' в поля таблиці TABLE припинено "," лінії закінчуються '\ п';
я змінити шлях і стіл його вдаючись але він дає мені помилку, що його синтаксис неправильний код 1064
може хто-небудь дати мені деякі радять, що робити
спасибі
стандартів
Привіт Стенлі, проблема полягає в одинарні лапки. Програмне забезпечення блогу тут переписує їх. Просто замініть 'і' з '
PS: команді вище, для безпосереднього завантаження файлу CSV в базу даних з MySQL рядка. Це добре, але не пов'язані з скрипта
Привіт усім!
Мабуть, скрипт працює ... Залежить, що він не записує дані в MySQL ...
Як і Кріс: сценарій завершується, і навіть виходи кількість записів, але не чіпає базу даних на всі ... але мені каже: Знайдено Всього 1 записів у цьому файлі CSV.
Що я роблю не так (їм нуб на PHP і MySQL)
Спасибі
Клаус
Всі привіт
Я використовую Drupal для створення нового веб-сайту, завдання в мене виникли прямо зараз, що мені потрібно, щоб імпортувати дані з CSV-файлу в базу даних MySQL, яка має спільні столи, тому деякі з полів, в які мені потрібні, щоб імпортувати дані CSV знаходяться в різних розділах одного і того ж база даних буде цей скрипт працювати на мене? Якщо не можете цей файл CSV бути імпортовані з використанням іншого методу?
Будь ласка, порадьте, дякую за будь-яку допомогу.
З повагою
Адріан
Дякуємо за сценарій. Дуже зрозуміло.
Як я можу змінити цей сценарій так, щоб вона витягує і зберігає файл CSV з Інтернету в MySQL?
@ Адріан
Привіт Адріана.
Drupal, як Ви зазначили, має складні структури таблиці. Залежно від того, яка інформація, яку ви імпортуєте, то дуже ймовірно, що ці дані повинні бути розбиті на кілька таблиць, як правило, із загальним зовнішнім ключем, такі як ідентифікатор вузла.
На жаль, сценарій вище, не допоможе це зробити.
@ Окіт
Привіт Окіт.
Швидше за все, ви можете позбутися від лінії 33-54 і замінити їх на цю один рядок:
$ Csvcontent = @ file_get_contents ("http:// ...");
замінити точок з відповідним URL-адресу (URL прямий в файл CSV)
@ Клауса
Привіт Клауса.
Чи має CSV дійсно містять одну запис?
Оскільки сценарій досягли стадії, коли він виводить кількість записів, я вважаю, він не забув, коли він підключений до бази даних (рядки 56-57) так що це не проблема.
Цілком можливо, що запит для вставки даних не вдається.
Спробуйте замінити лінії 88 з:
mysql_query ($ запиту) або померти (mysql_error ());
і перевірити, що помилка, яку ви отримаєте.
Добрий день,
Мені б дуже хотілося, щоб використовувати цей сценарій, але я не впевнений, що я роблю неправильно. Я отримую ту ж проблему згаданих вище з даними не завантажується в базу даних. Він знаходить правильну кількість рядків, але нічого не показує в дб.
Я змінив лінії 88 @ mysql_query ($ запиту) або померти (mysql_error ());
і отримати це повідомлення "Кількість стовбців не співпадає з кількістю значень у рядку 1"
@ Енді Бразертона : Це означає, що запит намагається вставити запис з числом стовпців, які не збігатися з таблицею бази даних.
1) Ви впевнені, що файл CSV має точно таку ж кількість стовпців, таблиці в базі даних?
2) Чи є роздільник полів в цьому файлі CSV дійсно кому? чи це вкладки, наприклад, або інший? Якщо це не кома, змініть значення змінної $ fieldseparator в рядку 12
3) таблиці повинні бути вже створена в базі даних, перш ніж намагатися завантажити дані в нього. Ти впевнений, що у вас є це?
Як же я порожній мій вже заповнені таблиці перед вставкою нового файлу?
або може я оновлення вже існуючих введення?
TRUNCATE, UPDATE? Як я можу отримати це в запиті?
Команда: усікання ім'я_таблиці.
Ви можете вкласти наступне в рядку 58:
@ Mysql_query ("усічення $ databasetable");
але це не є оборотним! так що будьте обережні
Привіт, це говорить мені, що кількість записів, але не покласти дані в базу даних
Сподіваюся, що ви можете допомогти
Натан
Мені потрібно завантажувати дані автоматично з віддаленого сервера. Його файл CSV, і мені потрібно розпакувати його і зберігати дані в базі даних MySQL, що я створив. Є кілька баз даних. Перший розділ нижче є однією з баз даних, які хтось допоміг мені, і це працює чудово. Я створив завдання, і він завантажує її автоматично за розкладом. Однак у мене є кілька баз даних і не можуть отримати інші роботи.
ЦЕЙ РОЗДІЛ НИЖЧЕ відмінно працює!
--------------------------
#! / BIN / Bash
deleteparam = '-видалити-після';
# Deleteparam = "
# Каталог = '-каталогу префікс = / $ HOME / моя_папка / моя_папка /'
каталог = "
# Userpwd = 'компанії-клієнта-користувача = бла-клієнта-пароль = бла "
ToUpper () {
Відлуння $ 1 | TR "[: нижче:]" "[: верхнє:]"
}
# Якщо [-Z "$ 1"], потім
# Ехо використання: $ 0 таблицю
# Вихід
# Fi
ZIP = ім'я файлу даних у віддаленому сервері
ZIP = `ToUpper $ ZIP`
# Файла в ZIP має один менше _
DATA = ім'я таблиці в моїй базі даних MySQL
DATA = `ToUpper $ DATA`
# Гт $ TABLE.csv.zip
# Гт $ data.csv
кд / $ HOME / моя_папка / моя_папка /
####### Отримати житлові
Wget -O $ ZIP.csv.zip
спати 10
####### Розпакуйте його
PWD
LS-ла
распаковать-о $ ZIP.csv.zip
спати 10
####### Завантажити його
Wget-багатослівний $ $ deleteparam каталог $ userpwd http://mywebsite/myfolder/import.php?table = $ DATA
сну 300
###### Видаляти файли
гт $ ZIP.csv.zip
гт $ data.csv
спати 10
_ ---------------------------
ВСЕ ЦЕ ПРАЦЮЄ НАД WONDERFUL
Це те, що мені потрібна допомога з
--------------------------
1. Мені потрібен сценарій, щоб додати до вище файл, який буде завантажувати фотографії. Якщо ви бачите нижче, я потребую скрипт, який автоматично отримує поточну дату і час, коли скрипт побіг. Там сервер тримає рис за останні 7 днів і постійно оновлюється. Після цього скрипт побіг вона буде завантажувати дані в таблицю, яку я створив.
2. Потім мені потрібно скрипт, який звертається до бази даних MySQL шукає записи, які є фотографії і потім отримати фактичні фотографії безпосередньо з віддалених серверів. Цей файл CSV НЕ завантажувати фотографії, просто дані, які я можу використовувати для запуску сценарію для отримання фотографій в даному місці. Див нижче.
Нижче наведено інструкції я отримав.
ІНСТРУКЦІЯ
Світлина дані завантажуються по протоколу HTTP. Фотографії дані оновлюються раз на добу і доступний для скачування у вигляді файлу CSV. Потім ви можете написати скрипт, використовуючи дані з файлу CSV, щоб вказати на зображення на нашому сервері зображень. Необхідно вказати значення для QUERY STRING last_updt> 'YYYYMMDD HH: MM: SS' для URL, щоб повернути дані. Поле last_updt є датою валютування в останній раз, що фотографія була змінена на лістинг.
Вам потрібно буде замінити user_code та тримачі пароль місце (XXXX) з Увійти повноваження надані для вас.
Крок 1: Щоб отримати первинний лістинг фото даних CSV-файлу перейдіть до URL нижче.
Крок 2: дані фотографії таблиці слід завантажити у форматі CSV.
Крок 3: Використання Y прапори і ML Номер в даних, які можна створити зворотне посилання на наш місцях зображення.
Нашою основною шлях до каталогу зображень виглядає наступним чином:
http://remoteserver/folder/folder/folder/Last3DigistsofML # / # лістингу. JPG
Наприклад, первинні фото для включення до переліку номер 1899430 знаходиться на
http://remoteserver/folder/folder/1/430/1899430.jpg
Наші додаткові зображення шлях до каталогу структура виглядає таким чином:
http://remoteserver/mlsphotos/full/PhotoPosition/Last3DigistsofML # / # лістингу _photoPosition.jpg
Наприклад, друге фото для включення до переліку номер 1899430 знаходиться на
http://remoteserver/folder/folder/2/430/1899430_2.jpg
Відмінний сценарій! Мені потрібно трохи почати стрибати від проекту я працював, і це зробили свою справу.
Я помітив щось дивне проте, я змінив скрипт для роботи з формою і я помітив, що для пошуку, останнє поле ставало buggered, тому що символ нового рядка (або \ г і \ п або обидва) як і раніше записується в базі даних MySQL.
З цією метою, якщо ви заміните:
$ Рядок = str_replace ("\ г ","",$ лінія);
з:
$ Рядок = str_replace ('\ г',",$ лінія);
він буде тримати повернення від проблеми, як і для нової лінії, я додав дещо, що дозволяє для вставки нових записів, але оновлення існуючих записів, так що ви не в кінцевому підсумку з дублюються записи. У верхній частині коду нижче, ви побачите, де я зробив те ж виправлення дійсно новий символ рядка.
$ Linemysql = вибухати ("','",$ linearray);
$ Newlinemysql = str_replace ('\ п',",$ linemysql);
якщо ($ addauto) {
Перемикач ($ databasetable) {
випадку ('адреса'):
$ Duplicatevals = "адреса = VALUES (адреса),
місто = VALUES (міста), стан = VALUES (держави),
поштовий = VALUES (поштова) ";
перерви;
випадку («власник»):
$ Duplicatevals = "OwnerName = VALUES (OwnerName),
housetype = VALUES (housetype),
addresskey = VALUES (addresskey) ";
перерви;
}
$ Запит = "вкласти в $ databasetable значення (",'$ newlinemysql ')
ON DUPLICATE KEY UPDATE
$ Duplicatevals ";
} Ще {
$ Запит = "вкласти в $ databasetable значення ('$ linemysql')
ON DUPLICATE KEY UPDATE
$ Duplicatevals ";
}
Крім того, в моїй формі я додав ім'я таблиці та не хочу я таблиці для [логічний] "addauto" чи ні, як один вхід з випадаючого (розділені комою), а потім розділити результат на початок simplecsvimport сценарій.
Нарешті, ви повинні пам'ятати, щоб встановити індексів в базі даних ", ON DUPLICATE ..." для роботи, авто кроком не буде працювати в цьому випадку, так що ви повинні встановити вторинний індекс за таблицями автоматичне збільшення, таблиць, що дон 'т приріст авто і володіють унікальними полями працювати з одним індексом, якщо це маршрут, який Ви хотіли б піти.
Я сподіваюся, що це хтось допомагає!
Ваше здоров'я!
Добрий день,
Зроблені деякі зміни. . Мій текстовий файл має 3 колонки, розділених "|" (труба) характер. Скрипт відображає файл з даними, підраховує рядка, але не входить до бази даних. Будь-які коментарі?
$ Csvcontent = FREAD ($ файлу, $ розміру);
fclose ($ файл);
$ CON = @ mysql_connect ($ DBHost, $ dbusername, $ dbuserpassword) або померти (mysql_error ());
@ Mysql_select_db ($ джерела даних) або померти (mysql_error ());
$ LineSeparator = "\ п";
$ Fieldseparator = "|";
$ Прямих = 0;
$ Запитів = "";
$ Linearray = Array ();
$ Count = 0;
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$ Count = $ Count + 1;
$ Прямих + +;
$ = Лінія обробки ($ рядок, "\ т");
$ Рядок = str_replace ("\ г ","",$ лінія);
/************************************
Ця лінія втечу особливий характер. видалити його, якщо записи вже біг в файл CSV
************************************/
$ Рядок = str_replace ("'"," \ '", $ рядок);
/*************************************/
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
$ Linemysql = вибухати (""",$ linearray);
якщо ($ addauto)
$ Запит = "вставити значення індикаторів ('$ підрахунок', '$ linemysql');";
ще
$ Запит = "вставити значення індикаторів ('$ linemysql');";
$ Запитів .= $ запиту. "\ П";
@ Mysql_query ($ запиту) або померти (mysql_error ());
луна "$ linemysql \ п";
}
я нічого не зрозумів як це працює від керуючого файлу. це, перш переглядати і вибирати файл, а потім представити, де мені потрібно, щоб зміни
Це дуже корисний код для мене ..
спасибі.
Як я можу отримати переглядати файл, а не вводити повний шлях до файлу ..
Будь ласка, допоможіть в цьому.
спасибі
Спасибі, цей код дійсно допомогло!
Як би я змінити його, щоб дозволити формі, яке буде відображатися в якому користувач переглядає і вибирає файл CSV для імпорту в таблицю?
А також як я можу зробити так, щоб кожен раз новий файл представляється було б змінити те, що в даний час зберігаються в таблиці?
Велике спасибі
[...] Що є деякі дуже гарні властивості, які я міг би використовувати, щоб допомогти мені вчити людей PL / SQL і XML. ITips і хитрості PHP скрипт для імпорту даних у форматі CSV mysqlPHP сценарій для імпорту CSV даних в MySQL ... [...]
Привіт всім,
Як утримувати ці лапки в CSV дати "день, місяць дати, 2010" і держава "пров, держава" в стовпець в моїй базі даних? Я бачу багато прикладів, але я не можу змусити його працювати. будь-яка допомога буде добре.
ак, 10037591,1 ", вівторок, 9 Березня 2010 15:55:16", 59,7151, -151.4434,2.7,75.90,32 ", півострова Кенай, штат Аляска"
THX
@ Кіш
поточний код не дозволяє перегляд для / завантаження файлів.
Ви можете просто помістити файл CSV в тому ж каталозі, що і сценарій PHP, а просто встановити змінну $ csvfile рівним імені файлу (без шляху)
@ Gary
Ви можете використовувати @ mysql_query ("усічення $ databasetable"); відразу після заяви @ mysql_select_db.
Але будьте обережні, тому що ця дія буде знищити дані і не є оборотним.
Як я можу пропустити перший рядок / рядки яких заголовок в файл CSV і вставте інші дані в БД?
Як Гері, я хочу, щоб перезаписати існуючі записи, але, оновивши її, не видаляючи всі дані в БД. Sp десь тут:
якщо ($ addauto)
$ Запит = "вкласти в $ databasetable значення (",'$ linemysql');";
ще
$ Запит = "вкласти в $ databasetable значення ('$ linemysql');";
Як би я перевірити, якщо запис існує, а потім оновлення, а не Вставте?
Сценарій читає додаткову рядок з файлу CSV. наприклад, якщо CSV-файлів є 25 записів Він показує, Є 26 записів. Чи можете ви сказати мені, де я неправильно?
Я додав перевірити, якщо це перша лінія і продовжити цикл, якщо його першому рядку.
спасибі
Наступні зробив трюк для мене:
LOAD DATA LOCAL INFILE LOW_PRIORITY
'C: \ \ Documents і Settings \ \ Адміністратор \ \ Desktop \ \ SigmaS1.csv "
INTO TABLE `MyDB`. `` ТуЬаИе
FIELDS ESCAPED BY '\ \'
TERMINATED BY ','
Можливо, укладеної BY '"'
ЛІНІЇ TERMINATED BY '\ г \ п'
(`Користувач`, `PWD`, `SNO`, `АМТ`, `ActiveRec`);
Це було дуже корисно для мене ... але я повинен був зробити модифікацію для читання великих файлів. Я був збентежений спочатку, але потім зрозумів, скрипт завантажує весь файл в пам'ять (не так?). Так ось налаштовану версію коду, яка читає рядки в одній за раз. він читає у файлах, які виглядають як
почати файл:
2,3, -1
1, -2,4
кінця файлу (з багатьма іншими значеннями). я хотів, щоб кожен лінії для запису таблиці та ідентифікатора з номером рядки, а також перший ідентифікатор представляють розмір таблиці (який не буде змінюватися пізніше).
<? PHP
/********************************/
/ * Код на http://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/ * Змінити записи нижче, щоб відображати відповідні значення
/********************************/
$ Databasehost = "локальний";
$ DatabaseName = "tomoku";
$ Databaseusername = "корінь";
$ Databasepassword = "корінь";
$ Fieldseparator = "\ п";
$ LineSeparator = "\ п";
/ / Цей код читає татамі файли в базу даних
$ CON = @ mysql_connect ($ databasehost, $ databaseusername, $ databasepassword) або померти (mysql_error ());
@ Mysql_select_db ($ DatabaseName) або померти (mysql_error ());
/ / Цей цикл по зв'язка файлів
для ($ г = 2, $ г <14; $ R + +) {
для ($ с = $ г, $ C
Якщо я обмежений доступ жорсткий диск клієнта як я буду завантажувати файл CSV для server.for приклад може покласти значення за замовчуванням для завантаження файлів контроль
Чудовий сценарій, але у мене виникли повторювані проблеми.
Після того як я запустити скрипт, він каже: "Знайдено Всього 1 записів у цьому файлі CSV.".
Я озирнувся назад в моєму столі, і він показує порожній.
Я перевірив, щоб переконатися, було правильне число стовпців і не було.
Будь ласка, допоможіть!
Спасибі,
Коултон
If you want to avoid inserting the first row, just play with the counter, for example:
$lines = 1; ( The value for the counter is 1)
$ Запитів = "";
$ Linearray = Array ();
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$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');”;
ще
$query = “insert into $databasetable values('$linemysql');”;
$ Запитів .= $ запиту. "\ П";
@ Mysql_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.
Спасибі
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());
$ Прямих = 0;
$ Запитів = "";
$ Linearray = Array ();
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$ Прямих + +;
$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
************************************/
$ Рядок = str_replace ("'"," \ '", $ рядок);
/*************************************/
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
$ Linemysql = вибухати ("','",$ linearray);
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
ще
$query = “insert into $databasetable values('$linemysql');”;
$ Запитів .= $ запиту. "\ П";
@ Mysql_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. Спасибі!
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”;
}
ще
{
?>
Type file name to import:
Дата
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.? Дякуємо.
@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. Any ideas?
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 ($ запиту);
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() . "\ П";
$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.
/ * Установка 1 для так, і 0 якщо немає. УВАГА: не встановлено в 1, якщо ви не впевнені.
/* 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? Якщо так безліч $ економити до 1.
/ * Дозвіл на файл повинен бути встановлений в 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)
$ Запитів = "";
$ Linearray = Array ();
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$lines++; ( Assigns the first line #2 (header)
if ($lines>=5){ (Start at #5 “anything higher or equal to 5?)
$ Запитів = "";
$ Linearray = Array ();
Еогеасп (спліт ($ LineSeparator, $ csvcontent) при $ рядок) {
$ Прямих + +;
$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
************************************/
$ Рядок = str_replace ("'"," \ '", $ рядок);
/*************************************/
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
$ Linemysql = вибухати ("','",$ linearray);
if($addauto)
$query = “insert into $databasetable values(”,'$linemysql');”;
ще
$query = “insert into $databasetable values('$linemysql');”;
$ Запитів .= $ запиту. "\ П";
/************************************
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() . "\ П";
$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
thanks
@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());
$ Прямих = 0;
$queries = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$ Прямих + +;
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 = вибухнути ($ fieldseparator, $ рядок);
$linemysql = implode("','",$linearray);
$query = "insert into $databasetable values('$linemysql');";
if($save) $queries .= $query . "\n";
@ Mysql_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());
$ Прямих = 0;
$ Запитів = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$ Прямих + +;
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
********************************************************/
$ Рядок = str_replace ("'"," \ '", $ рядок);
/*******************************************************/
$ Linearray = вибухнути ($ fieldseparator, $ рядок);
$linemysql = implode("','",$linearray);
$query = "insert into $databasetable values('$linemysql');";
if($save) $queries .= $query . "\n";
@ Mysql_query ($ запиту);
echo $lines."\n";
}
fclose($file);
$lines -= 3;
@mysql_close($con);
<>
I really could use some help in getting this to work…
Рон
@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
Thanks 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.
Дякуємо.
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
Спасибі!
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. Дякуємо.
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
Спасибі
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..
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
спасибі. the code provided really saving my time
Hi this code is great and easy to use, however I think I am doing something wrong:
I have a .csv that includes numbers and url's ect …the only row that your code will import into my sql is the first row which is just text as it is titles. I have taken that row out of the .cvs but the code is still not pulling the imformation – therefore I know that it is not a case of the code only pulling the 1st row …it is what is in the .csv rows… L
Someone please help me because I am completely stuck!
I need to write a script to do the following.
1. read data from csv files in a bunch of directories (the list of directories will grow in time)
2. the idea is that these csv files will be updated by car dealers and then uploaded to their respective directories thru ftp (I'm good with this bit as I will set the dir's and access)
3. problem comes in that at the dealer side the content of the files will keep changing. (some car info will remain / some will be deleted / and new ones will be added), this goes for all the dealers.
4. With every csv file they will upload images relating to the data in the csv files, so I will need to link this as well somehow.
5. the idea is to run this file with cron.php at set intervals to update the database (will ask how to do this when I get there)
What I've managed so far is to loop through the lot with the glob function, and adding the files, but my problem is updating the database. (cars removed from the csv files must not be deleted just set to sold, so we can keep that data for statistics)
Hope someone can point me in the right direction.
This is the code i've written so far:
PS: there are no headings in the csv files.
<?php
$username ="root";
$password = "myPasword";
$host = "localhost";
$table = "csv_table";
$conn = new mysqli("$host", "$username", "$password");
// echo "Connected to localhost" . "”;
mysql_select_db(“csvdb”) or die(mysql_error());
// echo “Connected to Database”;
?>
<?php
// Set variable for csv file path
$dir = "dealer_upload/*/*.csv";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
//echo "PATH AND FILENAME: " . $file . "”;
// Create the array
$fileTemp = $file;
$fp = fopen($fileTemp,'r');
$datas = array();
while (($data = fgetcsv($fp)) !== FALSE)
{
$stockNumber = trim($data[0]);
$make = trim($data[1]);
$model = trim($data[2]);
$derivative = trim($data[3]);
$series = trim($data[4]);
$reg = trim($data[5]);
$vin = trim($data[6]);
$driveAwayPrice = trim($data[7]);
$priceExcluding = trim($data[8]);
$specialPrice = trim($data[9]);
$year = trim($data[10]);
$kilometres = trim($data[11]);
$body = trim($data[12]);
$colour = trim($data[13]);
$engine = trim($data[14]);
$transmission = trim($data[15]);
$fuel = trim($data[16]);
$options = trim($data[17]);
$sellingPoints = trim($data[18]);
$nvic = trim($data[19]);
$redBook = trim($data[20]);
// Insert Data
mysql_query (“INSERT INTO $table (id_dealer, stockNumber, make, model, derivative, series, reg, vin, driveAwayPrice, priceExcluding, specialPrice, year, kilometres, body, colour, engine, transmission, fuel, options, sellingPoints, nvic, redBook)
VALUES ('$file', '$stockNumber', '$make', '$model', '$derivative', '$series', '$reg', '$vin', '$driveAwayPrice', '$priceExcluding' ,'$specialPrice' , '$year' , '$kilometres' , '$body', '$colour', '$engine', '$transmission', '$fuel', '$options', '$sellingPoints', '$nvic', '$redBook')
“)
or die (mysql_error());
}
}
?>