Меню

Ошибка базы данных codeigniter

CodeIgniter builds error reporting into your system through Exceptions, both the SPL collection, as
well as a few custom exceptions that are provided by the framework. Depending on your environment’s setup,
the default action when an error or exception is thrown is to display a detailed error report unless the application
is running under the production environment. In this case, a more generic message is displayed to
keep the best user experience for your users.

  • Using Exceptions

  • Configuration

    • Logging Exceptions

  • Framework Exceptions

    • PageNotFoundException

    • ConfigException

    • DatabaseException

    • RedirectException

  • Specify HTTP Status Code in Your Exception

  • Specify Exit Code in Your Exception

  • Logging Deprecation Warnings

Using Exceptions

This section is a quick overview for newer programmers, or for developers who are not experienced with using exceptions.

Exceptions are simply events that happen when the exception is “thrown”. This halts the current flow of the script, and
execution is then sent to the error handler which displays the appropriate error page:

<?php

throw new Exception('Some message goes here');

If you are calling a method that might throw an exception, you can catch that exception using a try/catch block:

<?php

try {
    $user = $userModel->find($id);
} catch (Exception $e) {
    exit($e->getMessage());
}

If the $userModel throws an exception, it is caught and the code within the catch block is executed. In this example,
the scripts dies, echoing the error message that the UserModel defined.

In the example above, we catch any type of Exception. If we only want to watch for specific types of exceptions, like
a UnknownFileException, we can specify that in the catch parameter. Any other exceptions that are thrown and are
not child classes of the caught exception will be passed on to the error handler:

<?php

try {
    $user = $userModel->find($id);
} catch (CodeIgniterUnknownFileException $e) {
    // do something here...
}

This can be handy for handling the error yourself, or for performing cleanup before the script ends. If you want
the error handler to function as normal, you can throw a new exception within the catch block:

<?php

try {
    $user = $userModel->find($id);
} catch (CodeIgniterUnknownFileException $e) {
    // do something here...

    throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}

Configuration

By default, CodeIgniter will display all errors in the development and testing environments, and will not
display any errors in the production environment. You can change this by setting the CI_ENVIRONMENT variable
in the .env file.

Important

Disabling error reporting DOES NOT stop logs from being written if there are errors.

Logging Exceptions

By default, all Exceptions other than 404 — Page Not Found exceptions are logged. This can be turned on and off
by setting the $log value of app/Config/Exceptions.php:

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;

class Exceptions extends BaseConfig
{
    public $log = true;
}

To ignore logging on other status codes, you can set the status code to ignore in the same file:

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;

class Exceptions extends BaseConfig
{
    public $ignoredCodes = [404];
}

Note

It is possible that logging still will not happen for exceptions if your current Log settings
are not set up to log critical errors, which all exceptions are logged as.

Framework Exceptions

The following framework exceptions are available:

PageNotFoundException

This is used to signal a 404, Page Not Found error. When thrown, the system will show the view found at
app/Views/errors/html/error_404.php. You should customize all of the error views for your site.
If, in app/Config/Routes.php, you have specified a 404 Override, that will be called instead of the standard
404 page:

<?php

if (! $page = $pageModel->find($id)) {
    throw CodeIgniterExceptionsPageNotFoundException::forPageNotFound();
}

You can pass a message into the exception that will be displayed in place of the default message on the 404 page.

ConfigException

This exception should be used when the values from the configuration class are invalid, or when the config class
is not the right type, etc:

<?php

throw new CodeIgniterExceptionsConfigException();

This provides an exit code of 3.

DatabaseException

This exception is thrown for database errors, such as when the database connection cannot be created,
or when it is temporarily lost:

<?php

throw new CodeIgniterDatabaseExceptionsDatabaseException();

This provides an exit code of 8.

RedirectException

This exception is a special case allowing for overriding of all other response routing and
forcing a redirect to a specific route or URL:

<?php

throw new CodeIgniterRouterExceptionsRedirectException($route);

$route may be a named route, relative URI, or a complete URL. You can also supply a
redirect code to use instead of the default (302, “temporary redirect”):

<?php

throw new CodeIgniterRouterExceptionsRedirectException($route, 301);

Specify HTTP Status Code in Your Exception

Since v4.3.0, you can specify the HTTP status code for your Exception class to implement
HTTPExceptionInterface.

When an exception implementing HTTPExceptionInterface is caught by CodeIgniter’s exception handler, the Exception code will become the HTTP status code.

Specify Exit Code in Your Exception

Since v4.3.0, you can specify the exit code for your Exception class to implement
HasExitCodeInterface.

When an exception implementing HasExitCodeInterface is caught by CodeIgniter’s exception handler, the code returned from the getExitCode() method will become the exit code.

Logging Deprecation Warnings

New in version 4.3.0.

By default, all errors reported by error_reporting() will be thrown as an ErrorException object. These
include both E_DEPRECATED and E_USER_DEPRECATED errors. With the surge in use of PHP 8.1+, many users
may see exceptions thrown for passing null to non-nullable arguments of internal functions.
To ease the migration to PHP 8.1, you can instruct CodeIgniter to log the deprecations instead of throwing them.

First, make sure your copy of ConfigExceptions is updated with the two new properties and set as follows:

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;
use PsrLogLogLevel;

class Exceptions extends BaseConfig
{
    // ... other properties

    public bool $logDeprecations       = true;
    public string $deprecationLogLevel = LogLevel::WARNING; // this should be one of the log levels supported by PSR-3
}

Next, depending on the log level you set in ConfigExceptions::$deprecationLogLevel, check whether the
logger threshold defined in ConfigLogger::$threshold covers the deprecation log level. If not, adjust
it accordingly.

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;

class Logger extends BaseConfig
{
    // .. other properties

    public $threshold = 5; // originally 4 but changed to 5 to log the warnings from the deprecations
}

After that, subsequent deprecations will be logged instead of thrown.

This feature also works with user deprecations:

<?php

@trigger_error('Do not use this class!', E_USER_DEPRECATED);
// Your logs should contain a record with a message like: "[DEPRECATED] Do not use this class!"

For testing your application you may want to always throw on deprecations. You may configure this by
setting the environment variable CODEIGNITER_SCREAM_DEPRECATIONS to a truthy value.

In sybase_driver.php

/**
* Manejador de Mensajes de Error Sybase
* Autor: Isaí Moreno
* Fecha: 06/Nov/2019
*/

static  $CODE_ERROR_SYBASE;

public static function SetCodeErrorSybase($Code) {
    if ($Code != 3621) {  /*No se toma en cuenta el código de command aborted*/
        CI_DB_sybase_driver::$CODE_ERROR_SYBASE = trim(CI_DB_sybase_driver::$CODE_ERROR_SYBASE.' '.$Code);       
    }
}

public static function GetCodeErrorSybase() {               
    return CI_DB_sybase_driver::$CODE_ERROR_SYBASE;
}

public static function msg_handler($msgnumber, $severity, $state, $line, $text)
{       
    log_message('info', 'CI_DB_sybase_driver - CODE ERROR ['.$msgnumber.'] Mensaje - '.$text);
    CI_DB_sybase_driver::SetCodeErrorSybase($msgnumber);   
}

// ------------------------------------------------------------------------

Add and modify the following methods in the same sybase_driver.php file

/**
 * The error message number
 *
 * @access  private
 * @return  integer
 */
function _error_number()
{
    // Are error numbers supported?
    return CI_DB_sybase_driver::GetCodeErrorSybase();
}

function _sybase_set_message_handler()
{
    // Are error numbers supported?     
    return sybase_set_message_handler('CI_DB_sybase_driver::msg_handler');
}

Implement in the function of a controller.

public function Eliminar_DUPLA(){       
    if($this->session->userdata($this->config->item('mycfg_session_object_name'))){     
        //***/
        $Operacion_Borrado_Exitosa=false;
        $this->db->trans_begin();

        $this->db->_sybase_set_message_handler();  <<<<<------- Activar Manejador de errores de sybase
        $Dupla_Eliminada=$this->Mi_Modelo->QUERY_Eliminar_Dupla($PARAMETROS);                   

        if ($Dupla_Eliminada){
            $this->db->trans_commit();
            MostrarNotificacion("Se eliminó DUPLA exitosamente","OK",true);
            $Operacion_Borrado_Exitosa=true;
        }else{
            $Error = $this->db->_error_number();  <<<<----- Obtengo el código de error de sybase para personilzar mensaje al usuario    
            $this->db->trans_rollback();                
            MostrarNotificacion("Ocurrio un error al intentar eliminar Dupla","Error",true);
            if ($Error == 547) {
                MostrarNotificacion("<strong>Código de error :[".$Error.']. No se puede eliminar documento Padre.</strong>',"Error",true);
            }  else {                   
                MostrarNotificacion("<strong>Código de Error :[".$Error.']</strong><br>',"Error",true);                 
            }
        }

        echo "@".Obtener_Contador_Notificaciones();
        if ($Operacion_Borrado_Exitosa){
            echo "@T";
        }else{
            echo "@F";
        }
    }else{
        redirect($this->router->default_controller);
    }

}

In the log you can check the codes and messages sent by the database server.

INFO - 2019-11-06 19:26:33 -> CI_DB_sybase_driver - CODE ERROR [547] Message - Dependent foreign key constraint violation in a referential integrity constraint. dbname = 'database', table name = 'mitabla', constraint name = 'FK_SR_RELAC_REFERENCE_SR_mitabla'. INFO - 2019-11-06 19:26:33 -> CI_DB_sybase_driver - CODE ERROR [3621] Message - Command has been aborted. ERROR - 2019-11-06 19:26:33 -> Query error: - Invalid query: delete from mitabla where ID = 1019.

Database errors are common while working with Codeignitor. It is mainly due to the wrong settings in the database configuration file.

As a part of our Server Management Services, we help our customers to fix similar database errors.

Today let’s discuss some tips to fix this error.

What causes the Codeigniter database error?

CodeIgniter has a configuration file that stores our database connection values like username, password, database name, etc. The config file is located at app/Config/Database.php. A sample format of this file is :

codeigniter database error

When the entries in the configuration contain some incorrect values, it triggers database errors. However, the exact error message triggered may depend on the incorrect entry. For instance, if the database name contains an extra space, the error message would be:

codeigniter database error

The common causes for this error include:

1. Improper database configuration in application/config/database.php
2. Non-existing database
3. No permission granted for the database user

Let us now look at the possible solutions for each case.

How to fix the Codeigniter database error

The method to fix the database error in Codeignitor depends on the exact error message that is triggered. For instance, a recent error message we received was:

A Database Error Occurred

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

This error message says that the access of the user with the given details is denied. To fix the error, first, we need to cross-check the database credentials configured in the configuration file. Make sure that there are no extra characters appended with the credentials in the file. Also, it is important to ensure that MySQL users have proper permissions set up to access the database.

Misspelled database name in the configuration file can also trigger this error. For instance, if an extra space is appended at the end of the database name. The system then, interprets it as a separate database name and the user receives a message that the database does not exist. Removal of the extra space from the database name will correct this error

[Need assistance to fix Database errors? We’ll help you.]

Conclusion

In short, the Codeigniter database error triggers normally due to invalid entries in the configuration file. Today, we discussed how our Support Engineers fixes the Codeignitor database error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Обработка ошибок

CodeIgniter позволяет создавать отчеты об ошибках в приложениях, используя функции описанные ниже. Кроме того, он имеет класс ведения журнала ошибок, который позволяет сохранять ошибки и отладочные сообщения в виде текстовых файлов.

Примечание

По умолчанию, CodeIgniter отображает все PHP ошибки. При желании, вы можете изменить это поведение как только завершите разработку. Вы найдете error_reporting() функцию расположенную в верхней части основного файла index.php. Отключение отчетов об ошибках не помешает записывать лог файлы при возникновении ошибок.

В отличии от большинства систем CodeIgniter, функциям ошибок свойственны простые процедурные интерфейсы, которые глобально доступны для всего приложения. Этот подход позволяет получать сообщения об ошибках, не беспокоясь об обзоре класс/функция .

CodeIgniter также возвращает код состояния, всякий раз когда ядро вызывает exit(). Этот код состояния отличный от HTTP кода состояния, и уведомляет другие процессы был ли сценарий завершен успешно или нет, и что за проблема повлекла прерывание. Эти значения определены в application/config/constants.php. Эти коды состояния наиболее полезны при использовании CLI параметров, возвращаемых надлежащий код серверного обеспечения помогающий отслеживать ваши скрипты и состояние ваших приложений.

Следующие функции позволяют генерировать ошибки:

show_error($message, $status_code, $heading = ‘Произошла Ошибка’)
Параметры:
  • $message (смешаный) – Сообщение об ошибке
  • $status_code (число) – HTTP код состояния ответа
  • $heading (строка) – Заголовок страницы с ошибкой
Возвращаемый тип:

пустота

Эта функция отобразит сообщение об ошибке через шаблон ошибки, соответствующего вашему исполнению:

application/views/errors/html/error_general.php

or:

application/views/errors/cli/error_general.php

Необязательный параметр $status_code обозначает что код состояния HTTP должен быть отправлен с ошибкой. Если $status_code меньше 100, код состояния HTTP будет иметь значение 500, и выход кода состояния будет иметь значение $status_code + EXIT__AUTO_MIN. Если это значение больше, чем EXIT__AUTO_MAX, или $status_code 100 или выше, выход кода состояния будет установлен EXIT_ERROR. Вы можете ознакомиться в application/config/constants.php более подробно.

show_404($page = », $log_error = TRUE)
Параметры:
  • $page (строка) – URI строка
  • $log_error (булево (bool)) – Нужно ли регистрировать ошибки
Возвращаемый тип:

пустота

Эта функция отобразит сообщение об ошибке 404 используя шаблон ошибки, соответствующего вашему исполнению:

application/views/errors/html/error_404.php

or:

application/views/errors/cli/error_404.php

Функция ожидает что ей передадут строку, являющуюся путем к файлу на ненайденную страницу. Выход кода состояния будет установлен в EXIT_UNKNOWN_FILE. Обратите внимание, CodeIgniter автоматически показывает ошибки 404 если контроллер не найден.

CodeIgniter автоматически регистрирует все show_404() вызовы. Необязательный второй параметр FALSE будет пропускать ведение журнала.

log_message($level, $message, $php_error = FALSE)
Параметры:
  • $level (строка) – Уровень журнала: ‘ошибка (error)’, ‘отладка (debug)’ или ‘инфо (info)’
  • $message (строка) – Сообщение журнала
  • $php_error (булево (bool)) – Записывать ли родные сообщения об ошибках PHP
Возвращаемый тип:

пустота

Эта функция позволяет записывать сообщения в лог файлы. Необходимо указать один из трех “уровней” первым параметром, указывая на тип сообщения (debug, error, info), с сообщением во втором параметре.

Example:

if ($some_var == '')
{
        log_message('error', 'Some variable did not contain a value.');
}
else
{
        log_message('debug', 'Some variable was correctly set');
}

log_message('info', 'The purpose of some variable is to provide some value.');

Существует три типа сообщений:

  1. Сообщения об ошибках. Эти фактические ошибки, такие как ошибки PHP или ошибки пользователя.
  2. Сообщения отладки. Это сообщения, которые помогают в отладке. Например, если класс был инициализирован, это может являться в качестве отладочной информации.
  3. Информационные сообщения. Они имеют самый низкий приоритет сообщений, просто давая информацию относительно некоторых процессов.

Примечание

Для того чтобы файл журнала на самом деле велся, категория logs/ должна быть доступна для записи. Кроме того, вы должны установить “порог” для ведения журналов application/config/config.php. Вы могли бы, например, записывать в журнал только сообщения об ошибках, а не двух других типов. Если вы установите его равным нулю, то ведение журнала будет отключено.

The same error I was getting when I upload my codeigniter project from localhost to Live server.

What solution I find is to make some changes into the application => config => database.php

Following is the database setting for the

localhost

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'creator',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Following database setting for

live server (Just demo, setting differ as per hosting provider)

1) First you have to create database.

2) find MySql Databases(or anything related database) on dashboard,

3) create new database and put database name, username, password.

4) export database from localhost

5) open phpmyadmin on live server and import it.

6) change the setting of application=>config=>database.php by using FTP client or dashboard.

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'mysql.hostingprovider.com',    
    'username' => 'abc.username',
    'password' => 'abc.password',
    'database' => 'abc.databasename',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

The same error I was getting when I upload my codeigniter project from localhost to Live server.

What solution I find is to make some changes into the application => config => database.php

Following is the database setting for the

localhost

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'creator',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Following database setting for

live server (Just demo, setting differ as per hosting provider)

1) First you have to create database.

2) find MySql Databases(or anything related database) on dashboard,

3) create new database and put database name, username, password.

4) export database from localhost

5) open phpmyadmin on live server and import it.

6) change the setting of application=>config=>database.php by using FTP client or dashboard.

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'mysql.hostingprovider.com',    
    'username' => 'abc.username',
    'password' => 'abc.password',
    'database' => 'abc.databasename',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Как обработать ошибки подключения к базе данных в Codeigniter?

Наверное, решение, которое я предложу, не самое лучшее с точки зрения архитектуры… но и сам CodeIgniter — не есть шедевр архитектурных решений в своей области.

Собственно, по теме:
Рассуждаем логически.
1. CodeIgniter написан на чистом PHP и ничего сверх того, что умеет сам PHP — CodeIgniter делать не может.
2. У нас какие-то сложности с обработкой ошибок подключения к БД на уровне CodeIgniter’a (какие именно — принципиального значения не имеет), но факт в том, что вариант CI вас чем-то не устраивает
3. Нам ничего не мешает подключаться к БД в обход стандартного механизма CI’а (я имею в виду, тестовый коннект, а не «вообще работать в обход стандартных механизмов»)

Далее, решение напрашивается само собой:
1. Подключаемся к базе «напрямую», например, с помощью mysqli_connect (с теми данными, которые ввел пользователь)
2.А Проверяем подключение и если «не коннект», проверяем ошибку, например с помощьюmysqli_error
2.Б Делаем то же самое, но получаем не сообщение об ошибке, а её код, функция mysqli_errno

Функция вернет Вам ошибку (текст) либо её номер (код), которые в дальнейшем Вы можете обрабатывать как душе угодно. При этом, «тестовый коннект» можно делать как внутри контроллера, там и вообще в каком-то отдельном файле, который существует отдельно от CI и служит например, для его инсталляции. Иными словами, дальнейшее зависит от Вашей фантазии и конечных потребностей.

P.S. Соотв., если изначально, MySQL не возвращает конкретную ошибку, например «неправильный именно логин» или «логин правильный, а вот пароль — нет» (что в принципе было бы логично, из соображений безопасности) — а Вам нужна именно такая дотошная степень детализации ошибки — получить её каким-то разумным способом не удастся, но ошибки вроде «MySQL-сервера по адресу N — нет» или «Учетные данные для подключения — не верные» — обработать труда не составит.

Main connection [MySQLi]: Access denied for user »@’localhost’ (using password: NO)
SYSTEMPATHDatabaseBaseConnection.php at line 400

393 break;
394 }
395 }
396 }
397
398 // We still don’t have a connection?
399 if (! $this->connID) {
400 throw new DatabaseException(sprintf(
401 ‘Unable to connect to the database.%s%s’,
402 PHP_EOL,
403 implode(PHP_EOL, $connectionErrors)
404 ));
405 }
406 }
407
Backtrace Server Request Response Files Memory
SYSTEMPATHDatabaseBaseConnection.php : 570 — CodeIgniterDatabaseBaseConnection->initialize ()

563 * @todo BC set $queryClass default as null in 4.1
564 /
565 public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = »)
566 {
567 $queryClass = $queryClass ?: $this->queryClass;
568
569 if (empty($this->connID)) {
570 $this->initialize();
571 }
572
573 /
*
574 * @var Query $query
575 */
576 $query = new $queryClass($this);
577
SYSTEMPATHDatabaseBaseBuilder.php : 1512 — CodeIgniterDatabaseBaseConnection->query ( arguments )

1505 $sql = $this->compileSelect($this->countString . $this->db->protectIdentifiers(‘numrows’));
1506 }
1507
1508 if ($this->testMode) {
1509 return $sql;
1510 }
1511
1512 $result = $this->db->query($sql, $this->binds, false);
1513
1514 if ($reset === true) {
1515 $this->resetSelect();
1516 } elseif (! isset($this->QBOrderBy)) {
1517 $this->QBOrderBy = $orderBy;
1518 }
1519
SYSTEMPATHModel.php : 509 — CodeIgniterDatabaseBaseBuilder->countAllResults ( arguments )

502 // When $reset === false, the $tempUseSoftDeletes will be
503 // dependant on $useSoftDeletes value because we don’t
504 // want to add the same «where» condition for the second time
505 $this->tempUseSoftDeletes = $reset
506 ? $this->useSoftDeletes
507 : ($this->useSoftDeletes ? false : $this->useSoftDeletes);
508
509 return $this->builder()->testMode($test)->countAllResults($reset);
510 }
511
512 /**
513 * Provides a shared instance of the Query Builder.
514 *
515 * @throws ModelException
516 *
SYSTEMPATHModel.php : 592 — CodeIgniterModel->countAllResults ()

585 protected function shouldUpdate($data): bool
586 {
587 // When useAutoIncrement feature is disabled check
588 // in the database if given record already exists
589 return parent::shouldUpdate($data)
590 && $this->useAutoIncrement
591 ? true
592 : $this->where($this->primaryKey, $this->getIdValue($data))->countAllResults() === 1;
593 }
594
595 /**
596 * Inserts data into the database. If an object is provided,
597 * it will attempt to convert it to an array.
598 *
599 * @param array|object|null $data
SYSTEMPATHBaseModel.php : 655 — CodeIgniterModel->shouldUpdate ( arguments )

648 */
649 public function save($data): bool
650 {
651 if (empty($data)) {
652 return true;
653 }
654
655 if ($this->shouldUpdate($data)) {
656 $response = $this->update($this->getIdValue($data), $data);
657 } else {
658 $response = $this->insert($data, false);
659
660 if ($response !== false) {
661 $response = true;
662 }
APPPATHControllersBlog.php : 50 — CodeIgniterBaseModel->save ( arguments )

43 ‘meta_title’ => ‘New Post ‘,
44 ‘title’ => ‘Create new post’,
45 ];
46
47 if($this->request->getMethod() == ‘post’)
48 {
49 $model = new BlogModel();
50 $model->save($_POST);
51 // print_r($_POST);
52 // exit;
53 }
54 return view(‘new_post’,$data);
55
56 }
57
SYSTEMPATHCodeIgniter.php : 802 — AppControllersBlog->new ()

795 {
796 // If this is a console request then use the input segments as parameters
797 $params = defined(‘SPARKED’) ? $this->request->getSegments() : $this->router->params(); // @phpstan-ignore-line
798
799 if (method_exists($class, ‘_remap’)) {
800 $output = $class->_remap($this->method, …$params);
801 } else {
802 $output = $class->{$this->method}(…$params);
803 }
804
805 $this->benchmark->stop(‘controller’);
806
807 return $output;
808 }
809
SYSTEMPATHCodeIgniter.php : 399 — CodeIgniterCodeIgniter->runController ( arguments )

392 if (! method_exists($controller, ‘_remap’) && ! is_callable([$controller, $this->method], false)) {
393 throw PageNotFoundException::forMethodNotFound($this->method);
394 }
395
396 // Is there a «post_controller_constructor» event?
397 Events::trigger(‘post_controller_constructor’);
398
399 $returned = $this->runController($controller);
400 } else {
401 $this->benchmark->stop(‘controller_constructor’);
402 $this->benchmark->stop(‘controller’);
403 }
404
405 // If $returned is a string, then the controller output something,
406 // probably a view, instead of echoing it directly. Send it along
SYSTEMPATHCodeIgniter.php : 317 — CodeIgniterCodeIgniter->handleRequest ( arguments )

310 $this->response->pretend($this->useSafeOutput)->send();
311 $this->callExit(EXIT_SUCCESS);
312
313 return;
314 }
315
316 try {
317 return $this->handleRequest($routes, $cacheConfig, $returnResponse);
318 } catch (RedirectException $e) {
319 $logger = Services::logger();
320 $logger->info(‘REDIRECTED ROUTE at ‘ . $e->getMessage());
321
322 // If the route is a ‘redirect’ route, it throws
323 // the exception with the $to as the message
324 $this->response->redirect(base_url($e->getMessage()), ‘auto’, $e->getCode());
FCPATHindex.php : 37 — CodeIgniterCodeIgniter->run ()

30 /*
31 *—————————————————————
32 * LAUNCH THE APPLICATION
33 *—————————————————————
34 * Now that everything is setup, it’s time to actually fire
35 * up the engines and make this app do its thang.
36 */
37 $app->run();
38

11 ответов

Попробуйте эти функции CI

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)

Oskenso Kashi
21 окт. 2011, в 04:41

Поделиться

Возможно, это:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

RayJ
18 июнь 2013, в 06:27

Поделиться

Вы должны отключить отладку для базы данных в config/database.php →

$db['default']['db_debug'] = FALSE;

Это лучше для безопасности вашего сайта.

Kabir Hossain
12 янв. 2014, в 12:35

Поделиться

Я знаю, что эта ветка устарела, но на всякий случай у кого-то еще есть эта проблема. Это трюк, который я использовал, не касаясь классов CI db. Оставьте свой отладочный файл и в вашем файле просмотра ошибок, выделите исключение.

Итак, у вас db config, у вас есть:

$db['default']['db_debug'] = true;

Затем в вашем файле представления ошибок db моя находится в application/errors/error_db.php, замените все содержимое следующим образом:

<?php
$message = preg_replace('/(</?p>)+/', ' ', $message);
throw new Exception("Database error occured with message : {$message}");

?>

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

tlogbon
19 дек. 2014, в 13:48

Поделиться

Я создал для этого простую библиотеку:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class exceptions {

    public function checkForError() {
        get_instance()->load->database();
        $error = get_instance()->db->error();
        if ($error['code'])
            throw new MySQLException($error);
    }
}

abstract class UserException extends Exception {
    public abstract function getUserMessage();
}

class MySQLException extends UserException {
    private $errorNumber;
    private $errorMessage;

    public function __construct(array $error) {
        $this->errorNumber = "Error Code(" . $error['code'] . ")";
        $this->errorMessage = $error['message'];
    }

    public function getUserMessage() {
        return array(
            "error" => array (
                "code" => $this->errorNumber,
                "message" => $this->errorMessage
            )
        );
    }

}

Пример запроса:

function insertId($id){
    $data = array(
        'id' => $id,
    );

    $this->db->insert('test', $data);
    $this->exceptions->checkForError();
    return $this->db->insert_id();
}

И я могу это поймать в своем контроллере:

 try {
     $this->insertThings->insertId("1");
 } catch (UserException $error){
     //do whatever you want when there is an mysql error

 }

da1lbi3
27 дек. 2016, в 19:00

Поделиться

Поместите этот код в файл MY_Exceptions.php в папку application/core:

<?php

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

/**
 * Class dealing with errors as exceptions
 */
class MY_Exceptions extends CI_Exceptions
{

    /**
     * Force exception throwing on erros
     */
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        set_status_header($status_code);

        $message = implode(" / ", (!is_array($message)) ? array($message) : $message);

        throw new CiError($message);
    }

}

/**
 * Captured error from Code Igniter
 */
class CiError extends Exception
{

}

Это приведет к тому, что все ошибки восходящего кода будут рассматриваться как исключение (CiError). Затем включите всю отладку базы данных:

$db['default']['db_debug'] = true;

Adriano Gonçalves
29 янв. 2016, в 15:45

Поделиться

Используйте его

    $this->db->_error_message(); 

Лучше найти ошибку. После завершения вашего сайта.
Закройте сообщения об ошибках
используя его

    $db['default']['db_debug'] = FALSE;

Вы измените его в своей папке config.php

Kabir Hossain
26 янв. 2014, в 13:01

Поделиться

пример, который работал для меня:

$query = "some buggy sql statement";

$this->db->db_debug = false;

if([email protected]$this->db->query($query))
{
    $error = $this->db->error();
    // do something in error case
}else{
    // do something in success case
}
...

Лучший

dlg_
04 фев. 2019, в 17:21

Поделиться

Отключить отладку ошибок.

    $data_user = $this->getDataUser();
    $id_user   = $this->getId_user();

    $this->db->db_debug = false;
    $this->db->where(['id' => $id_user]);
    $res = $this->db->update(self::$table, $data_user['user']);

    if(!$res)
    {
        $error = $this->db->error();
        return $error;
        //return array $error['code'] & $error['message']
    }
    else
    {
        return 1;
    }

the_martux
25 сен. 2018, в 12:30

Поделиться

Если один использует PDO, дополнительно ко всем ответам выше.

Я регистрирую свои ошибки тихо, как показано ниже

        $q = $this->db->conn_id->prepare($query);

        if($q instanceof PDOStatement) {
           // go on with bind values and execute

        } else {

          $dbError = $this->db->error();
          $this->Logger_model->logError('Db Error', date('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' -  '.'Message: '.$dbError['message']);

        }

blumanski
25 март 2018, в 02:26

Поделиться

Ещё вопросы

  • 0CSS конфликт между 2 скриптами
  • 1Windows Phone 8.1 масштабирование изображения
  • 0PHP Получить значения из ассоциативного массива на основе списка соответствующих ключей
  • 1Android-виджет, не кликабельный
  • 1Элемент PivotItem Анимация
  • 0Zurb Foundation Использование пространства по обе стороны от 12 колонок
  • 1Не могу включить уведомления в angular 4, используя firebase
  • 1передача значений между двумя потоками, не мешая друг другу
  • 0Как получить доступ к свойствам области вложенных угловых директив
  • 1android — можно ли заставить действие пользователя эмулировать аппаратную кнопку «Назад»?
  • 1Разрезать текст в каждом контейнере
  • 0Импорт событий из MS Office 365 (PHP)
  • 0Проверьте, действительно ли строка, содержащая html, пуста
  • 1Как использовать изображения в качестве частиц?
  • 0Передача объекта в качестве аргумента в конструктор класса
  • 0Использование нескольких каруселей с CaroufredSel
  • 1Распределенный Erlang, как мне генерировать уникальные имена узлов?
  • 0Как выбрать комментарии с дочерними комментариями из MySQL?
  • 0Как убрать все границы в таблице?
  • 1При создании исполняемого файла с использованием Python2.7 и cx_Freeze я получаю следующую ошибку, связанную сPython.Runtime.dll «
  • 0DOM не обновляется при изменении значения переменной контроллера
  • 1Как добавить событие WPF treeView Node Click, чтобы получить значение узла
  • 1Проблемы с устройствами на Android с OpenGL ES GL 11
  • 1javascript / redux: как избежать нуля при получении состояния?
  • 1Ошибка создания каталога … Java, Android
  • 1Синхронизированный раздел внутри конструктора и различия синхронизированного конструктора
  • 0Почему strtotime () ничего не возвращает в следующем сценарии?
  • 0Этот скрипт загрузки защищен паролем?
  • 0инкрементное значение внутри массива массивов (если ключ не существует, установите его равным 1)
  • 0Получение обратного вызова с HTML на пост jQuery
  • 1Метод в Vue запускается дважды по клику
  • 00x80070002 при попытке установить браузер по умолчанию
  • 0не могу получить данные JSON из URL
  • 0JavaScript не видит первый клик?
  • 1Вложения под Файловая система против баз данных?
  • 0Ячейка таблицы HTML — восстановление значений
  • 1Как решить NoClassDefFoundError в сервлете Java?
  • 0Как изменить файл JavaScript, который добавляет функцию к $ .fn для использования requirejs?
  • 0OpenCV — остановка программы при выполнении шага определения ключевых точек изображения
  • 1Интерактивная 3d графика с использованием Python или JavaScript
  • 1Обработка Python любого исключения дает ошибку KeyboardInterrupt
  • 1Момент js вычесть 2 раза
  • 0Оптимизировать — Как получить доступ к названию варианта
  • 0Как оформить определенный тд в каждой третьей строке таблицы?
  • 1Данные InlineAutoData для аргумента конкретного параметра
  • 0PHP получает запрос, ничего не возвращающий
  • 1Добавить функциональность веб-сервисов в текущее работающее Java-приложение
  • 1GSON «NoClassDefFoundError com / google / gson / Gson»
  • 1Пустой канал в плагине страницы Facebook (встроенный виджет каналов)
  • 1Добавьте или объявите две plotOptions в старших диаграммах для Синхронизированной диаграммы

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка аутентификация не пройдена пожалуйста попробуйте снова
  • Ошибка базы данных 1064