Jump to content
  • 0

Не записываются данные в таблицу из codeigniter в sql


vitaxastifler
 Share

Question

Всем привет,ребятки,вопрос жизни и смерти(
Мне очень надо перегнать б/д MARC SQL в б/д сайта!!!
Предыдущий программист делал это,он написал на скрипт на codeiniter.
В 2-х словах он обьяснил как он работает и пропал безвести(
Работает скрипт так:Выбираем базу (марка) (Б/Д Марка в формате .html) и просто нажимаем кнопку конвертировать,codeigniter автоматом записывает данные в б/д (phpmyadmin) сайта.
Всё вроде и работает но,в базу не записывается(
Вот исходники,подскажите пожалуйста(
Огромное спасибо!

1-й скрин здесь сам вид программы 
http://hostingkartinok.com/show-imag...809d0a7f12b121

D:\xampp\htdocs\konverter\application\views\load.php

<html lang="ru-ru" slick-uniqueid="1" xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru-ru"><head><meta content="text/html; charset=utf-8" http-equiv="content-type"><meta content="index, follow" name="robots"><title>Konverter</title></head><body>    <?php        echo form_open_multipart('load_db/dbconvert');        echo form_upload('filename');        echo '<br />';        echo form_radio('dbname', 'БД аудіо-відео матеріалів', FALSE);        echo 'kffd;';        echo form_radio('dbname', 'БД методичних матеріалів', FALSE);        echo 'method;';        echo form_radio('dbname', 'БД книг', FALSE);        echo 'book;<br />';        echo form_radio('dbname', 'БД статей із періодики', FALSE);        echo 'bibl;';        //echo form_radio('dbname', 'period', FALSE);        //echo 'period;';        echo form_radio('dbname', 'БД краєзнавчих матеріалів', FALSE);        echo 'kray;<br/>';        echo form_submit('submit', 'konvert');        echo form_close();    ?>       </body></html>

D:\xampp\htdocs\konverter\application\config\database.php
 

 <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');/*| ——————————————————————-| DATABASE CONNECTIVITY SETTINGS| ——————————————————————-| This file will contain the settings needed to access your database.|| For complete instructions please consult the 'Database Connection'| page of the User Guide.|| ——————————————————————-| EXPLANATION OF VARIABLES| ——————————————————————-||   ['hostname'] The hostname of your database server.|   ['username'] The username used to connect to the database|   ['password'] The password used to connect to the database|   ['database'] The name of the database you want to connect to|   ['dbdriver'] The database type. ie: mysql.  Currently supported:                 mysql, mysqli, postgre, odbc, mssql, sqlite, oci8|   ['dbprefix'] You can add an optional prefix, which will be added|                to the table name when using the  Active Record class|   ['pconnect'] TRUE/FALSE - Whether to use a persistent connection|   ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.|   ['cache_on'] TRUE/FALSE - Enables/disables query caching|   ['cachedir'] The path to the folder where cache files should be stored|   ['char_set'] The character set used in communicating with the database|   ['dbcollat'] The character collation used in communicating with the database|                NOTE: For MySQL and MySQLi databases, this setting is only used|                as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7|                (and in table creation queries made with DB Forge).|                There is an incompatibility in PHP with mysql_real_escape_string() which|                can make your site vulnerable to SQL injection if you are using a|                multi-byte character set and are running versions lower than these.|                Sites using Latin-1 or UTF-8 database character set and collation are unaffected.|   ['swap_pre'] A default table prefix that should be swapped with the dbprefix|   ['autoinit'] Whether or not to automatically initialize the database.|   ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections|                           - good for ensuring strict SQL while developing|| The $active_group variable lets you choose which connection group to| make active.  By default there is only one group (the 'default' group).|| The $active_record variables lets you determine whether or not to load| the active record class*/ $active_group = 'default';$active_record = TRUE; $db['default']['hostname'] = 'localhost';$db['default']['username'] = 'admin';$db['default']['password'] = 'admin';$db['default']['database'] = 'chobdck_database';$db['default']['dbdriver'] = 'mysql';$db['default']['dbprefix'] = 'chobd';$db['default']['pconnect'] = TRUE;$db['default']['db_debug'] = TRUE;$db['default']['cache_on'] = FALSE;$db['default']['cachedir'] = '';$db['default']['char_set'] = 'utf8';$db['default']['dbcollat'] = 'utf8_general_ci';$db['default']['swap_pre'] = '';$db['default']['autoinit'] = TRUE;$db['default']['stricton'] = FALSE;  /* End of file database.php *//* Location: ./application/config/database.php */

D:\xampp\htdocs\konverter\application\models\konverter_model.php
 

 <?phpif (!defined('BASEPATH')) exit('Нет доступа к скрипту'); /** *  */class Konverter_model extends CI_Model {       function __construct() {        parent::__construct();        $this->load->database();    }       function index($data) {        $this->db->insert('chobdck_database', $data);    }} ?>

D:\xampp\htdocs\konverter\application\controllers\load_db.php

 

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class Load_db extends CI_Controller {public function __construct() {parent::__construct();$this->load->model('Konverter_model');}function index() {$this->load->view('load');}function dbconvert() {//uplode file$filename = $_FILES['filename']['name'];move_uploaded_file($_FILES['filename']['tmp_name'], $_SERVER["DOCUMENT_ROOT"] . base_url() . 'upload/' . $filename);$dbname = $_POST['dbname'];//array from html$file = read_file('upload/'. $filename);$file = explode('</TR>', $file);//cleaning data and sortforeach ($file as $field => $item) {$item = explode('', iconv('windows-1251', 'UTF-8', trim(strip_tags($item))));//delete first three cell from arrayfor($i=1; $i<3; $i++) {array_shift($item);}            echo "<hr /><pre>";            var_dump($item);            echo "</pre><hr />";//array numbers of the fields;$fields = array('author'    => array('100' => 'a'),'title'     => array('245' => ''),'pub_info'  => array('250' => ''),'publisher' => array('260' => ''),'pages'     => array('300' => ''),'seria'     => array('440' => ''),'person'    => array('600' => 'a'),'geograf'   => array('651' => 'a'),'rubric'    => array('650' => 'a'),'keywords'  => array('653' => 'a'),'source'    => array('773' => ''));foreach ($fields as $field_name => $field_index) {$result[$field_name] = $this->check_fields($item, $field_index);}$result['dbname'] = $dbname;//$this->Konverter_model->index($result);/*echo "<hr /><pre>";var_dump($result);echo "</pre><hr />";*/}}function check_fields($item, $field_index) {global $field;foreach ($field_index as $str_index => $sub_str_index) {foreach ($item as $line) {$pos = strpos($line, "$str_index");if(strstr($line, "$str_index") and $pos == 0) {if(!empty($sub_str_index)) {$field = '';$sub_lines = explode('', $line);foreach ($sub_lines as $sub_line) {$pos = strpos($sub_line, "$sub_str_index");if(strstr($sub_line, "$sub_str_index") and $pos == 0) {$field .= str_replace("$sub_str_index", '', $sub_line);}}break;} else {$field = $line;$field = str_replace("$str_index", '', $field);$field = str_replace("", '', $field);$field = substr_replace($field, '', 0, 2);if("$str_index" == '245') {$field = substr_replace($field, '', 0, 1);$field = str_replace('a', ' ', $field);$field = str_replace('b', ' : ', $field);$field = str_replace('c', ' / ', $field);$field = str_replace('n', ' ', $field);$field = str_replace('p', ' : ', $field);} elseif("$str_index" == '250') {$len = strlen($field) - 1;if(strripos($field, '.') == $len) {$field = substr_replace($field, '', $len, $len);}$field = str_replace('a', '. - ', $field);$field = str_replace('b', ', ', $field);} elseif("$str_index" == '260') {$len = strlen($field) - 1;if(strripos($field, '.') == $len) {$field = substr_replace($field, '', $len, $len);}$field = str_replace('a', '. - ', $field);$field = str_replace('b', ' : ', $field);$field = str_replace('c', ', ', $field);} elseif("$str_index" == '300') {$len = strlen($field) - 1;if(strripos($field, '.') == $len) {$field = substr_replace($field, '', $len, $len);}$field = str_replace('a', '. - ', $field);$field = str_replace('b', ' : ', $field);} elseif("$str_index" == '440') {//$field добавить скобки$field = str_replace('a', '. - b', $field);$len = strlen($field);$field = str_replace('b', '(', $field);$field = substr_replace($field, ')', $len, $len); } elseif("$str_index" == '773') {$field = str_replace('t', ' // ', $field);$field = str_replace('d', '. -', $field);$field = str_replace('g', '. -', $field);} $field = preg_replace('//', ' ', $field);}break;} else {$field = '';}}}return $field;}}?>

D:\xampp\htdocs\konverter\application\libraries\Konverter_lib.php

 <?phpif (!defined('BASEPATH')) exit('Нет доступа к скрипту'); class Konverter_lib {       function check_fields($item, $value) {        global $field;         foreach ($value as $field_num_index => $sub_string_index) {             foreach($item as $line) {                               if (preg_match($field_num_index, $line)) {                $line = explode('', $line);                    foreach ($line as $key => $sub_str) {                         $pos = strpos($sub_str, $sub_string_index);                        if (preg_match('/a/', $sub_str) and $pos == 0) {                             $field[] = $sub_str;                        } else {                             $field[] = ' ';                        }                                            }                               }                   }           }    return $field;     }} ?>

Вот сюда должно записаться!
http://hostingkartinok.com/show-imag...193c2204fefc1a

Edited by vitaxastifler
Link to comment
Share on other sites

10 answers to this question

Recommended Posts

  • 0

LunatiK

Да,я это исправил,но выпала вот такая ошибка!

Что скажете?

http://hostingkartinok.com/show-image.php?id=1e236a23171e81b31c00160bdf88d927

Код "дб драйвера")

 

Исправил....!

Edited by vitaxastifler
Link to comment
Share on other sites

  • 0

    function index($data) {        $this->db->insert('chobdck_database', $data);    }

Где chobdck_database должна быть существующая таблица. И этот код не соответствует ошибке которую вы предоставили.

 

Ибо на скриншоте вам явно сказано chobdne' tupi

Делайте, удачи :)

  • Like 1
Link to comment
Share on other sites

  • 0

парни,всё работает кроме одного(

Заливаю б/д и выдаёт такую ошибку

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 3474 bytes) in D:\xampp\htdocs\konverter\application\controllers\load_db.php on line 21

 

 

Где 21 строка это 

	$file = explode('</TR>', $file);

Вот собственно ввесь код

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Load_db extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Konverter_model');
}

function index() {
$this->load->view('load');
}

function dbconvert() {
//uplode file
$filename = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $_SERVER["DOCUMENT_ROOT"] . base_url() . 'upload/' . $filename);
$dbname = $_POST['dbname'];
//array from html
$file = read_file('upload/'. $filename);
$file = explode('', $file);
//cleaning data and sort
foreach ($file as $field => $item) {
$item = explode('', iconv('windows-1251', 'UTF-8', trim(strip_tags($item))));
//delete first three cell from array
for($i=1; $i<3; $i++) {
array_shift($item);
}
echo "

";            var_dump($item);            echo "

";
//array numbers of the fields;
$fields = array(
'author' => array('100' => 'a'),
'title' => array('245' => ''),
'pub_info' => array('250' => ''),
'publisher' => array('260' => ''),
'pages' => array('300' => ''),
'seria' => array('440' => ''),
'person' => array('600' => 'a'),
'geograf' => array('651' => 'a'),
'rubric' => array('650' => 'a'),
'keywords' => array('653' => 'a'),
'source' => array('773' => '')
);
foreach ($fields as $field_name => $field_index) {
$result[$field_name] = $this->check_fields($item, $field_index);

}

$result['dbname'] = $dbname;
$this->Konverter_model->index($result);
echo "

";			var_dump($result);			echo "

";
}

}

function check_fields($item, $field_index) {
global $field;
foreach ($field_index as $str_index => $sub_str_index) {
foreach ($item as $line) {
$pos = strpos($line, "$str_index");
if(strstr($line, "$str_index") and $pos == 0) {
if(!empty($sub_str_index)) {
$field = '';
$sub_lines = explode('', $line);
foreach ($sub_lines as $sub_line) {
$pos = strpos($sub_line, "$sub_str_index");
if(strstr($sub_line, "$sub_str_index") and $pos == 0) {
$field .= str_replace("$sub_str_index", '', $sub_line);
}
}
break;
} else {

$field = $line;
$field = str_replace("$str_index", '', $field);
$field = str_replace("", '', $field);
$field = substr_replace($field, '', 0, 2);
if("$str_index" == '245') {
$field = substr_replace($field, '', 0, 1);
$field = str_replace('a', ' ', $field);
$field = str_replace('b', ' : ', $field);
$field = str_replace('c', ' / ', $field);
$field = str_replace('n', ' ', $field);
$field = str_replace('p', ' : ', $field);
} elseif("$str_index" == '250') {
$len = strlen($field) - 1;
if(strripos($field, '.') == $len) {
$field = substr_replace($field, '', $len, $len);
}
$field = str_replace('a', '. - ', $field);
$field = str_replace('b', ', ', $field);
} elseif("$str_index" == '260') {
$len = strlen($field) - 1;
if(strripos($field, '.') == $len) {
$field = substr_replace($field, '', $len, $len);
}
$field = str_replace('a', '. - ', $field);
$field = str_replace('b', ' : ', $field);
$field = str_replace('c', ', ', $field);
} elseif("$str_index" == '300') {
$len = strlen($field) - 1;
if(strripos($field, '.') == $len) {
$field = substr_replace($field, '', $len, $len);
}
$field = str_replace('a', '. - ', $field);
$field = str_replace('b', ' : ', $field);
} elseif("$str_index" == '440') {
//$field добавить скобки
$field = str_replace('a', '. - b', $field);
$len = strlen($field);
$field = str_replace('b', '(', $field);
$field = substr_replace($field, ')', $len, $len);
} elseif("$str_index" == '773') {
$field = str_replace('t', ' // ', $field);
$field = str_replace('d', '. -', $field);
$field = str_replace('g', '. -', $field);

}
$field = preg_replace('//', ' ', $field);



}
break;
} else {
$field = '';
}
}

}
return $field;
}
}

?>

Link to comment
Share on other sites

  • 0

В памати при обработки ваших 73Мб скрипт выходит за пределы 128Мб разрешённые в настройках php.ini. Поэтому и не хочет, либо дайте больше памяти, либо оптимизируйте скрипт.

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy