Модераторы: skyboy, MoLeX, Aliance, ksnk
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Проблема с занесением данных в MySQL, из файла выбираются данные и заносятся 
:(
    Опции темы
liliputochka
Дата 8.6.2010, 11:54 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 154
Регистрация: 16.3.2006
Где: Волгоград

Репутация: нет
Всего: нет



Доброго дня!
 Дело в том, что я извлекаю данные из файла, с помощью фунции 
Код
explode("|", $str);
 разделяю данные на массив, и из этого массива уже формирую sql-запрос.
Выглядит это следующим образом:
Код

include_once "tball_function.php";

$file0 = "tball\\stok.txt";
$file1 = "tball\\list.txt";
$file2 = "tball\\duplicateSKU.txt";
$file3 = "tball\\new_list.txt";

RewriteTxtFile($file0, $file1);
Replacement($file1);

$handle0 = fopen($file3, "rt") or die("Can't open file $file1");
$handle1 = fopen($file2, "w") or die("Can't open file $file2");
fwrite($handle1, "Tball duplicate sku:\n");
$conn = connecting();

$j = 0;
while(!feof($handle0)){
    $sku_array = array();
    $data = fgets($handle0, 4096);
    $data_matrix = explode("|", $data);
    list($sku, $title, $weight, $quantity, $category, , $developer, , , , $cost, $length, $width, $height, , $description, $LongDescription) = $data_matrix;
    $sku_array[$j] = $sku;
    $j++;
//--------- sku
    $temp = $sku;
    $sku = "T-".$temp;
//--------- price
    $price = retailPrice($cost);
//--------- categoryID
    $categoryID = oursCat($category, $price);
//----------- size
    $size = $length." x ".$width." x ".$height." inches";
//----------- quantity
    if($quantity == 0)    $quantity = 1;
//----------- description
    $description = addslashes($description);
    $LongDescription = addslashes($LongDescription);
    $title = addslashes($title);
    $sku = addslashes($sku);
    $weight = addslashes($weight);
    $cost = addslashes($cost);
    $price = addslashes($price);
    
    if($conn != 0){
        for($i = 0; $i < count($sku_array); $i++){
            if($temp == $sku_array[$i]){
                fwrite($handle1, $temp."\n");
            }
            else{
                $str = "insert into `user_products` values(NULL, '".$categoryID."', '".$title."', '".$sku."', '".$weight."', '".$cost."', '".$price."', 'Tball', '', '".$developer."', '".$size."', ".$quantity.", '".$description."', '".$LongDescription."')";
                mysql_query($str, $conn) or die("Can't insert:".mysql_error());
            }
        }
    }
}

disconnecting($conn);
fclose($handle1);
fclose($handle0);

Функция Replacement($file1)
Код

function Replacement($file1){
    $handle1 = fopen($file1, "rt");
    $handle2 = fopen("tball\\new_list.txt", "w");
    
    while(!feof($handle1)){
        $str = fgets($handle1, 4096);
        $matrix = explode("\n", $str);
        for($j = 0; $j < count($matrix); $j++){
            fwrite($handle2, $matrix[$j]);
            fwrite($handle2, "<br>");
        }
    }
    
    fclose($handle2);
    fclose($handle1);
}

Функция RewriteTxtFile($file0, $file1) особой смысловой нагрузки не несет. Она лишь убирает заголовки столбцов в файле, чтобы были только данные.
Данные в базу не заносятся. Не могу найти причину. Помогите пожалуйста.
PM MAIL   Вверх
patap
Дата 8.6.2010, 12:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 893
Регистрация: 7.5.2005
Где: Украина, Зп

Репутация: 26
Всего: 40



ну, а mysql_error() что-то выдает?


--------------------
На боку кобура болталась, сзади шашка отцовская звякала. 
Впереди меня все хохотало, а позади все плакало (с)
PM MAIL ICQ   Вверх
liliputochka
Дата 8.6.2010, 12:14 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 154
Регистрация: 16.3.2006
Где: Волгоград

Репутация: нет
Всего: нет



Вот это:
Код

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's outstanding reliability & equipment protection.

Я вывела предыдущий sql-запрос, чтобы найти эту самую ошибку. Он выглядит следующим образом:
Код

insert into `user_products` values(NULL, '0', '\"EV2510K \",\"Reach Easy Rolling Massager\",\" 4.00\",\" 0\",\"MASSAGERS\",\"037988563517\",\"PANASONIC\",\"0\",\"\",\"\",\" 26.00\",\"\",\"\",\"\",\"CHINA\",\"PANASONIC REACH EASY ROLLING MASSAGER \",\"Three Different Kinds of Vibration Massage

Promote circulation with stroking massage using three different massage heads:



* Massage Rollers - gives wide area and comfortable massage to the Back, Lower Back and Shoulders.

* Point Massager - for stiffness on the shoulders.

* Wide Surface - provides a gentle rubbing massage to the arms or legs.



Reach Easy Design

Target hard-to-reach areas with this special elbow-angled design that lets you access your lower, middle and upper back more easily.



When applied, the point massager focuses on a specific area of the body and applies the massage technique strongly to one point.



* Point Massager Yes (for shiatsu-type massage--ideal for relaxing shoulders)

* Massage Roller Yes (for stroking massage to relax the back and lower back)

* Wavy Surface Yes (for gentle treatment of the arms and legs)

* Reach Easy Design Yes (with Flex Head)

* Head Vibration Distance .08\"\" (2mm)

* Vibration Rate Strong: Approx. 6,300 times/min.

* Gentle: Approx. 5,000 times/min.

* Power Source AC 120V, 60Hz

* Power Consumption 3W

* Dimensions (H x W x D) 18.5\'\' x 3.3\'\' x 7.1\'\'

* Weight 1.66 lbs\"', 'T-been certified as “Works with iPhone” to integrate its communication and entertainment capabilities into your car system.



* To connect iPod, please use the cable included with your iPod.



* Please visit the Clarion website for iPod models that are compatible with the CZ200.





Rear USB for Cable-linked MP3/WMA Playback



The USB input on the rear of the unit can be used to connect a USB memory stick that contains MP3 and WMA music files. It’s an easy way to share music files between your car and your PC.





H.M.I. Balances Design and Usability



Clarion’s quest for a superior H.M.I. (Human-Machine Interface) resulted in this year’s distinctive “starburst” control button array. Buttons are clustered symbolically for intuitive operation, with a large rotary volume control that is blue illuminated for easy recognition and sensational looks.





BeatEQ for User Customizable Sound



In addition to providing 3 preset equalization patterns — BASS BOOST, IMPACT, and EXCITE — Clarion’s BeatEQ even lets you freely customize the level and range of the bass, midrange and treble portions of each pattern. You can tune the sound to your liking, depending on the category of music, for a more fulfilling listening experience.





LargeView



Low Pass Filter for Subwoofer



Switching on the Low Pass Filter (LPF) will send only the low frequency range through specified outputs to ensure superb performance with a connected subwoofer. A must if you have or plan to add a subwoofer to your system.



Steering Wheel Remote Control Ready



By connecting an optional 3rd-party adapter, the CZ200 is compatible with many of the steering wheel remote controls pre-installed on various makes of cars. So you can upgrade from your factory audio system without losing the convenience of the existing remote.



* Optional Interface Box Required\"', '\"GRP12D4 \",\"GRP12D4 Crunch subwoofer 12 in. DVC 500 Watt\",\" 25.00\",\" 1\",\"WOOFERS\",\"806576214786\",\"CRUNCH\",\"0\",\"\",\"\",\" 34.00\",\"\",\"\",\"\",\"CHINA\",\"CRUNCH GROUNDPOUNDER 12\"\" DVC 500 WOOFER \",\"Crunch GRP12D4 Crunch Groundpounder 12 in. DVC 500 Watt Car Woofer. GRP subwoofers offer a single four-Ohm 12\'\' and DVC configurations. All models feature a treated paper cone and excellent Crunch performance. \"', '', '0', 'Tball', '', '', ' x x inches', 1, '', '')

Попробовала его в PhpMyAdmin - вставил строку.
PM MAIL   Вверх
MoLeX
Дата 8.6.2010, 12:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Местный пингвин
****


Профиль
Группа: Модератор
Сообщений: 4076
Регистрация: 17.5.2007

Репутация: 46
Всего: 140



liliputochka, mysql_real_escape_string()


--------------------
Amazing  smile 
PM MAIL WWW ICQ   Вверх
liliputochka
Дата 8.6.2010, 12:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 154
Регистрация: 16.3.2006
Где: Волгоград

Репутация: нет
Всего: нет



MoLeX, честно сказать - не помогло. :( Возникает таже ошибка.
PM MAIL   Вверх
нуп
Дата 8.6.2010, 13:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Ботокодер
**


Профиль
Группа: Участник
Сообщений: 987
Регистрация: 22.6.2009
Где: Кременчуг

Репутация: нет
Всего: 33



Да ошибка в инсерте, данные не правильно заносишь

Добавлено через 35 секунд
наверное обычное число заносишь с кавычками 
PM MAIL   Вверх
MoLeX
Дата 8.6.2010, 13:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Местный пингвин
****


Профиль
Группа: Модератор
Сообщений: 4076
Регистрация: 17.5.2007

Репутация: 46
Всего: 140



liliputochka, код измененный


--------------------
Amazing  smile 
PM MAIL WWW ICQ   Вверх
liliputochka
Дата 8.6.2010, 13:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 154
Регистрация: 16.3.2006
Где: Волгоград

Репутация: нет
Всего: нет



Вы нуп обсолютно правы. Я действительно заношу числа в кавычках. Но что мне делать, когда там где в запросе должено стоять число - ничего нет?

Добавлено через 49 секунд
Код измененный:
Код

while(!feof($handle0)){
    $sku_array = array();
    $data = fgets($handle0, 4096);
    $data_matrix = explode("|", $data);
    //print_r($data_matrix);
    list($sku, $title, $weight, $quantity, $category, , $developer, , , , $cost, $length, $width, $height, , $description, $LongDescription) = $data_matrix;
    $sku_array[$j] = $sku;
    $j++;
//--------- sku
    $temp = $sku;
    $sku = "T-".$temp;
//--------- price
    $price = retailPrice($cost);
//--------- categoryID
    $categoryID = oursCat($category, $price);
//----------- size
    $size = $length." x ".$width." x ".$height." inches";
//----------- quantity
    if($quantity == 0)    $quantity = 1;
//----------- description
    $description = mysql_real_escape_string($description);
    $LongDescription = mysql_real_escape_string($LongDescription);
    //echo "Title:".$title."<br>";
    $title = mysql_real_escape_string($title);
    $sku = mysql_real_escape_string($sku);
    $weight = mysql_real_escape_string($weight);
    $cost = mysql_real_escape_string($cost);
    $price = mysql_real_escape_string($price);
    
    if($conn != 0){
        for($i = 0; $i < count($sku_array); $i++){
            if($temp == $sku_array[$i]){
                fwrite($handle1, $temp."\n");
            }
            else{
                $str = "insert into `user_products` values(NULL, '".$categoryID."', '".$title."', '".$sku."', '".$weight."', '".$cost."', '".$price."', 'Tball', '', '".$developer."', '".$size."', ".$quantity.", '".$description."', '".$LongDescription."')";
                echo $str."<br>";
                mysql_query($str, $conn) or die("Can't insert:".mysql_error());
            }
        }
    }
}

PM MAIL   Вверх
нуп
Дата 8.6.2010, 13:14 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Ботокодер
**


Профиль
Группа: Участник
Сообщений: 987
Регистрация: 22.6.2009
Где: Кременчуг

Репутация: нет
Всего: 33



Проверку делать, если не число, то ставишь ему 0. Нужно заносить без кавычек только интегер. И в базе в полях выставь стандартные значения 0 smile 
PM MAIL   Вверх
liliputochka
Дата 8.6.2010, 13:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 154
Регистрация: 16.3.2006
Где: Волгоград

Репутация: нет
Всего: нет



Спасибо нуп
Только теперь у меня появилась другая ошибка:
Код

Can't insert:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\"GRP12D4 \",\"GRP12D4 Crunch subwoofer 12 in. DVC 500 Watt\",\" 25.00' at line 1

Вот в таком запросе:
Код

insert into `user_products` values(NULL, '0', '\"EV2510K \",\"Reach Easy Rolling Massager\",\" 4.00\",\" 0\",\"MASSAGERS\",\"037988563517\",\"PANASONIC\",\"0\",\"\",\"\",\" 26.00\",\"\",\"\",\"\",\"CHINA\",\"PANASONIC REACH EASY ROLLING MASSAGER \",\"Three Different Kinds of Vibration Massage

Promote circulation with stroking massage using three different massage heads:



* Massage Rollers - gives wide area and comfortable massage to the Back, Lower Back and Shoulders.

* Point Massager - for stiffness on the shoulders.

* Wide Surface - provides a gentle rubbing massage to the arms or legs.



Reach Easy Design

Target hard-to-reach areas with this special elbow-angled design that lets you access your lower, middle and upper back more easily.



When applied, the point massager focuses on a specific area of the body and applies the massage technique strongly to one point.



* Point Massager Yes (for shiatsu-type massage--ideal for relaxing shoulders)

* Massage Roller Yes (for stroking massage to relax the back and lower back)

* Wavy Surface Yes (for gentle treatment of the arms and legs)

* Reach Easy Design Yes (with Flex Head)

* Head Vibration Distance .08\"\" (2mm)

* Vibration Rate Strong: Approx. 6,300 times/min.

* Gentle: Approx. 5,000 times/min.

* Power Source AC 120V, 60Hz

* Power Consumption 3W

* Dimensions (H x W x D) 18.5\'\' x 3.3\'\' x 7.1\'\'

* Weight 1.66 lbs\"', 'T-been certified as “Works with iPhone” to integrate its communication and entertainment capabilities into your car system.



* To connect iPod, please use the cable included with your iPod.



* Please visit the Clarion website for iPod models that are compatible with the CZ200.





Rear USB for Cable-linked MP3/WMA Playback



The USB input on the rear of the unit can be used to connect a USB memory stick that contains MP3 and WMA music files. It’s an easy way to share music files between your car and your PC.





H.M.I. Balances Design and Usability



Clarion’s quest for a superior H.M.I. (Human-Machine Interface) resulted in this year’s distinctive “starburst” control button array. Buttons are clustered symbolically for intuitive operation, with a large rotary volume control that is blue illuminated for easy recognition and sensational looks.





BeatEQ for User Customizable Sound



In addition to providing 3 preset equalization patterns — BASS BOOST, IMPACT, and EXCITE — Clarion’s BeatEQ even lets you freely customize the level and range of the bass, midrange and treble portions of each pattern. You can tune the sound to your liking, depending on the category of music, for a more fulfilling listening experience.





LargeView



Low Pass Filter for Subwoofer



Switching on the Low Pass Filter (LPF) will send only the low frequency range through specified outputs to ensure superb performance with a connected subwoofer. A must if you have or plan to add a subwoofer to your system.



Steering Wheel Remote Control Ready



By connecting an optional 3rd-party adapter, the CZ200 is compatible with many of the steering wheel remote controls pre-installed on various makes of cars. So you can upgrade from your factory audio system without losing the convenience of the existing remote.



* Optional Interface Box Required\"', \"GRP12D4 \",\"GRP12D4 Crunch subwoofer 12 in. DVC 500 Watt\",\" 25.00\",\" 1\",\"WOOFERS\",\"806576214786\",\"CRUNCH\",\"0\",\"\",\"\",\" 34.00\",\"\",\"\",\"\",\"CHINA\",\"CRUNCH GROUNDPOUNDER 12\"\" DVC 500 WOOFER \",\"Crunch GRP12D4 Crunch Groundpounder 12 in. DVC 500 Watt Car Woofer. GRP subwoofers offer a single four-Ohm 12\'\' and DVC configurations. All models feature a treated paper cone and excellent Crunch performance. \", '', '0', 'Tball', '', '', ' x x inches', 1, '', '')

PM MAIL   Вверх
Severyanin
Дата 10.6.2010, 17:14 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Исследователь
**


Профиль
Группа: Участник
Сообщений: 554
Регистрация: 31.7.2007
Где: Россия, Омск

Репутация: нет
Всего: 9



Я бы очень посоветовал в данном случае распечатывать строки запросов перед тем, как они попадают в mysql_query, сразу можно будет по синтаксису понять, что не так. Если сразу не видно - отладить это дело в mysql, а лучше - в phpmyadmin. Пока не выполнится корректно, а потом уже править свой код до соответствия генерируемого запроса тому, который выполнился 


--------------------
"Звонким вереском скроются наши следы, и не вспомнят о них. Кто поверит нам, рыцарям павшей звезды из отвергнутых книг? Пусть в узоре времен ни стихов. ни имен, но напомнит забывшим их полуночный крик." Тэм Гринхилл
"Ужели суслик твоего коварства нагадит в плов доверья моего?". Л.Филатов 
PM MAIL WWW ICQ   Вверх
ksnk
Дата 10.6.2010, 17:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


прохожий
****


Профиль
Группа: Комодератор
Сообщений: 6855
Регистрация: 13.4.2007
Где: СПб

Репутация: 96
Всего: 386



надо бы при составлени запроса пользовать функцию mysql_real_escape_string, а не самостийно квотить двойные кавычки

Добавлено через 7 минут и 36 секунд
кавычка где-то потерялась одинарная 


--------------------
Человеку свойственно ошибаться, программисту свойственно ошибаться профессионально ! user posted image
PM MAIL WWW Skype   Вверх
liliputochka
Дата 11.6.2010, 14:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 154
Регистрация: 16.3.2006
Где: Волгоград

Репутация: нет
Всего: нет



Severyanin благодарю за совет, я именно так и делаю: распечатываю, проверяю сначала функцией mysql_query(), затем там где выводятся ошибки - пробую sql-запрос в phpMyAdmin. В нем выполняются, а функция не хочет выполнять!

Простите ksnk, насколько я смогла увидеть, кавычки присутствуют в сообщение об ошибки, но в запросе их нет.
PM MAIL   Вверх
Noviy
Дата 13.6.2010, 18:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 98
Регистрация: 29.11.2007

Репутация: нет
Всего: нет



liliputochka, посмотрите внизу запроса
Код

* Optional Interface Box Required\"', \"GRP12D4 \",

У вас нет кавычек для строки  \"GRP12D4 \",...
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "PHP"
Aliance
IZ@TOP
skyboy
SamDark
MoLeX

Новичкам:

  • PHP редакторы собираются и обсуждаются здесь
  • Электронные книги по PHP, документацию можно найти здесь
  • Интерпретатор PHP, полную документацию можно скачать на PHP.NET

Важно:

  • Не брезгуйте пользоваться тегами [code=php]КОД[/code] для повышения читабельности текста/кода.
  • Перед созданием новой темы воспользуйтесь поиском и загляните в FAQ
  • Действия модераторов можно обсудить здесь

Внимание:

  • Темы "ищу скрипт", "подскажите скрипт" и т.п. будут переноситься в форум "Web-технологии"
  • Темы с именами: "Срочно", "помогите", "не знаю как делать" будут УДАЛЯТЬСЯ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, IZ@TOP, skyboy, SamDark, MoLeX, awers.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | PHP: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0655 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.