Codeigniter mysql error

Is there a way to make CI throw an exception when it encounters a DB error instead of displaying a message like: A Database Error Occurred Error Number: 1054 Unknown column 'foo' in '

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.

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.

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»;

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

9 votes

19 answers

Get the solution ↓↓↓

Is there a way to make CI throw an exception when it encounters a DB error instead of displaying a message like:

A Database Error Occurred Error Number: 1054
Unknown column ‘foo’ in ‘where clause’ SELECT * FROM (FooBar) WHEREfoo = ‘1’

NOTE: I only want this to happen in one controller. In the other controllers, I’m happy for it to display the DB error messages.

2021-10-12

Write your answer


998

votes

Answer

Solution:

Try these CI functions

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

UPDATE FOR CODEIGNITER 3

Functions are deprecated, useerror() instead:

$this->db->error(); 


926

votes

Answer

Solution:

Maybe this:

$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


672

votes


197

votes

Answer

Solution:

You must turn debug off for database in config/database.php ->

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

It is better for your website security.


312

votes

Answer

Solution:

I know this thread is old, but just in case there’s someone else having this issue. This is a trick I used without touching the CI db classes. Leave your debug on and in your error view file, throw an exception.

So in you db config, you have :

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

Then in your db error view file, mine is inapplication/errors/error_db.php replace all content with the following:

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

?>

Since the view file will be called, the error will always get thrown as an exception, you may later add different views for different environment.


767

votes

Answer

Solution:

an example that worked for me:

$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
}
...

Best


789

votes

Answer

Solution:

I have created an simple library for that:

<?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
            )
        );
    }

}

The example query:

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

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

And I can catch it this way in my controller:

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

 }


351

votes

Answer

Solution:

Put this code in a file called MY_Exceptions.php in application/core folder:

<?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
{

}

It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:

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


912

votes

Answer

Solution:

Use it

    $this->db->_error_message(); 

It is better for finding error.After completing your site.
Close the error messages
using it

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

You will change it in your config folder’s database.php


411

votes

Answer

Solution:

Disable debugging of errors.

    $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;
    }


957

votes

Answer

Solution:

If one uses PDO, additional to all the answers above.

I log my errors silently as below

        $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']);

        }


585

votes

Answer

Solution:

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

{-code-2}

Implement in the function of a controller.

{-code-3}

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

{-code-4}








823

votes

Answer

—|||/**
* 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’);
}|||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);
}
}|||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.


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-10-12

Link To Source

Link To Answer
People are also looking for solutions of the problem: dompdf image not found or type unknown

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Я использую CI просто отлично, используя драйвер MySQL. Я хочу использовать драйвер mysqli вместо этого, но как только я его поменяю (просто добавьте «i» в конец mysql и добавьте номер порта), я получаю следующее сообщение об ошибке

Использование: CI 2.0.2 php 5.3.4 Apache / 2.2.17 (Unix) mysql 5.5.13 mysql.default_port 3306

Для меня проблема была в файле php.ini. Свойство mysql.default_socket указывало на файл в несуществующей директории. Свойство указывало на /var/mysql/mysql.sock но в OSX файл находился в /tmp/mysql.sock .

Как только я обновил запись в php.ini и перезапустил веб-сервер, проблема была решена.

Я думаю, что что-то не так с PHP-конфигурацией.
Во-первых, отлаживайте соединение с базой данных, используя этот скрипт в конце ./config/database.php :

 ... ... ... echo '<pre>'; print_r($db['default']); echo '</pre>'; echo 'Connecting to database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('Cannot connect to the database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '<br /> Connected OK:' ; die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); по ... ... ... echo '<pre>'; print_r($db['default']); echo '</pre>'; echo 'Connecting to database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('Cannot connect to the database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '<br /> Connected OK:' ; die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); по ... ... ... echo '<pre>'; print_r($db['default']); echo '</pre>'; echo 'Connecting to database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('Cannot connect to the database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '<br /> Connected OK:' ; die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); по ... ... ... echo '<pre>'; print_r($db['default']); echo '</pre>'; echo 'Connecting to database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('Cannot connect to the database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '<br /> Connected OK:' ; die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); по ... ... ... echo '<pre>'; print_r($db['default']); echo '</pre>'; echo 'Connecting to database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('Cannot connect to the database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '<br /> Connected OK:' ; die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); 

Тогда посмотрим, в чем проблема.

Сегодня я столкнулся с такой проблемой на реальном сервере, и я решил проблему, изменяющую эту строку

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

в

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

Я решил проблему, изменив

$db['default']['pconnect'] = TRUE; TO $db['default']['pconnect'] = FALSE;

в /application/config/database.php

SET $db['default']['db_debug'] в FALSE вместо TRUE.

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

Если это все, что вы изменили, у вас может не быть установлен или включен драйвер mysqli в вашей конфигурации PHP.

Проверьте его наличие с помощью phpinfo () или в файле php.ini (extension = php_mysqli ….).

Задача решена!

У меня был весь мой сайт, настроенный первым в XAMMP, тогда мне пришлось перенести его на LAMP, в установку SUSE LAMP, где я получил эту ошибку.

Проблема в том, что эти параметры в файле database.php не должны инициализироваться. Просто оставьте имя пользователя и пароль пустым. Это все.

(Мое первое и хромое предположение было бы из-за старой версии mysql, поскольку встроенные установки поставляются со старыми версиями.

(CI 3) Для меня все изменилось:

 'hostname' => 'localhost' to 'hostname' => '127.0.0.1' 

Если вы использовали это для защиты своего сервера: http://www.thonky.com/how-to/prevent-base-64-decode-hack/

А потом Code Igniter needs mysql_pconnect() in order to run ошибка: Code Igniter needs mysql_pconnect() in order to run .

Я понял это, как только я понял, что все сайты Code Igniter на сервере были сломаны, поэтому это была не проблема локализованного подключения.

Измените $db['default']['dbdriver'] = 'mysql' на $db['default']['dbdriver'] = 'mysqli'

Я решил это. В моем случае я просто изменил свою конфигурацию. «hostname» стал «localhost»

 $active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; 

Я использую CI просто отлично, используя драйвер MySQL. Вместо этого я хочу использовать драйвер MySQL, но как только я его изменил (просто добавьте «i в конец MySQL» и добавил номер порта), я получаю следующее сообщение об ошибке

Произошла ошибка базы данных

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

Имя файла: core/Loader.php

Номер строки: 232

моя настройка выглядит так:

$db['default']['hostname'] = $hostname;
$db['default']['username'] = $username;
$db['default']['password'] = $password;
$db['default']['database'] = $database;
$db['default']['dbdriver'] = 'mysqli';
$db['default']['port']     = "3306";  
$db['default']['dbprefix'] = '';
$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; 

where
$hostname = 'localhost';
$username = 'myusernamegoeshere';
$password = 'mypasswordgoeshere';
$database = 'mydatabasenamegoeshere'; 

Я использую:

CI 2.0.2 php 5.3.4 Apache/2.2.17 (Unix) mysql 5.5.13 mysql.default_port 3306

Я делаю что-то неправильно?

Спасибо,

31 авг. 2011, в 10:33

Поделиться

Источник

12 ответов

Для меня проблема была в файле php.ini. Свойство mysql.default_socket указывало на файл в несуществующей директории. Свойство указывало на /var/mysql/mysql.sock, но в OSX файл находился в /tmp/mysql.sock.

Как только я обновил запись в php.ini и перезапустил веб-сервер, проблема была решена.

ken
15 июнь 2012, в 01:16

Поделиться

Я думаю, что что-то не так с PHP-конфигурацией.
Во-первых, отлаживайте соединение с базой данных, используя этот script в конце. /config/database.php:

...
  ...
  ...
  echo '<pre>';
  print_r($db['default']);
  echo '</pre>';

  echo 'Connecting to database: ' .$db['default']['database'];
  $dbh=mysql_connect
  (
    $db['default']['hostname'],
    $db['default']['username'],
    $db['default']['password'])
    or die('Cannot connect to the database because: ' . mysql_error());
    mysql_select_db ($db['default']['database']);

    echo '<br />   Connected OK:'  ;
    die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); 

Затем посмотрите, что это проблема.

Valeh Hajiyev
10 янв. 2012, в 19:54

Поделиться

Сегодня я столкнулся с такой проблемой на реальном сервере, и я решил проблему с изменением этой строки

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

to

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

imsyedahmed
21 март 2013, в 21:54

Поделиться

Я решил проблему, изменив

$db['default']['pconnect'] = TRUE; TO
$db['default']['pconnect'] = FALSE;

в /application/config/database.php

kamal
19 фев. 2013, в 17:52

Поделиться

SET $db['default']['db_debug'] в FALSE вместо TRUE.

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

Bhumi Singhal
16 июль 2013, в 20:18

Поделиться

Если это все, что вы изменили, у вас может не быть установлен или включен драйвер mysqli в вашей конфигурации PHP.

Проверьте его наличие с помощью phpinfo() или в файле php.ini(extension = php_mysqli….).

Craig A Rodway
31 авг. 2011, в 09:34

Поделиться

(CI 3) Для меня работа изменилась:

'hostname' => 'localhost' to 'hostname' => '127.0.0.1'

Shina
29 нояб. 2015, в 11:43

Поделиться

Проблема решена!

У меня был весь мой сайт, настроенный первым в XAMMP, тогда мне пришлось перенести его на LAMP, в установку SUSE LAMP, где я получил эту ошибку.

Проблема заключается в том, что эти параметры в файле database.php не должны быть инициализированы.
Просто оставьте имя пользователя и пароль пустым.
Это просто.

(Мое первое и хромое предположение было бы тем, что из-за старой версии mysql, поскольку встроенные установки поставляются со старыми версиями.

Helena
23 фев. 2012, в 15:39

Поделиться

Расширение @Valeh Hajiyev отличный и четкий ответ для тестов драйвера mysqli:

Отладьте соединение с базой данных, используя этот скрипт в конце. /config/database.php:

/* Your db config here */ 
$db['default'] = array(
  // ...
  'dbdriver'     => 'mysqli',
  // ...
);

/* Connection test: */

echo '<pre>';
print_r($db['default']);
echo '</pre>';

echo 'Connecting to database: ' .$db['default']['database'];

$mysqli_connection = new MySQLi($db['default']['hostname'],
                                $db['default']['username'],
                                $db['default']['password'], 
                                $db['default']['database']);

if ($mysqli_connection->connect_error) {
   echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
   echo "Connected.";
}
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);

MarcM
17 янв. 2019, в 14:30

Поделиться

Измените $db['default']['dbdriver'] = 'mysql' на $db['default']['dbdriver'] = 'mysqli'

Bappi Datta
14 июнь 2014, в 09:35

Поделиться

Если вы использовали это для защиты своего сервера:
http://www.thonky.com/how-to/prevent-base-64-decode-hack/

И затем получена ошибка: Code Igniter needs mysql_pconnect() in order to run.

Я понял, как только я понял, что все веб-сайты Code Igniter на сервере были сломаны, поэтому это была не проблема локализованного подключения.

Lawrence
29 фев. 2012, в 18:48

Поделиться

Я решил это. В моем случае я просто изменил свою конфигурацию. «hostname» стал «localhost»

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';

achie
20 дек. 2012, в 10:47

Поделиться

Ещё вопросы

  • 0Перестаньте MJPEG с IP-камеры Axis
  • 0Моя директива использует изолированную область, но все еще выбирает данные из области контроллера
  • 0jQuery выбирает класс, только если он содержится в другом классе
  • 0Jquery вызывает функцию из внешнего файла [дубликата]
  • 1Одиночная JSP с другим классом действия
  • 1Слово соответствия регулярному выражению, кроме случаев, когда оно является частью URL
  • 0C ++ Помощь при разработке класса ConstArray и Array, которые представляют собой своего рода динамический массив значений int
  • 1@ Inject не вводит и вызывает исключение NullPointerException при использовании компонентного сканирования
  • 0Современная анимация CSS / JQuery Bubble
  • 0Ошибка sql syntanx Я хочу сравнить две таблицы данных в одном запросе
  • 1Проверка содержимого EditText, как только пользователь вводит данные
  • 1Мне нужно отредактировать текстовый файл с непостоянной структурой. Попытка использовать панд, это лучший инструмент для работы?
  • 0Селекторы jQuery корректно экранируют
  • 1Перенаправление Spring Security 3.1 на вход в систему не работает, когда происходит вызов метода сервлета (контроллера) после истечения времени ожидания
  • 0PHP создать команду копирования, как phpmyadmin
  • 1Расчет расстояния и рыскания между маркером ArUco и камерой?
  • 1Почему я не могу разобрать вложение javamail с помощью toString?
  • 0Как получить представление навигационной ссылки в пагинации?
  • 0Передайте параметры через JSON в модальное всплывающее окно в ASP.NET MVC3
  • 1Отображение здоровья врага над врагом [работает, но не реально]?
  • 0Выборка и группировка данных путем сравнения времени
  • 0Крайний случай: метод Kendo Web UI Grid «Выбрать» не работает должным образом
  • 1Добавление загрузочного звука в Froyo 2.2 Droid
  • 1Не повторяйте DAO! Использование универсального DAO
  • 0ios Slider по умолчанию использует последний слайд
  • 0AngularJS: контроллер с фабрикой
  • 0Node.js API с Express & MySQL — поиск нескольких значений в параметре поиска
  • 0Строка jQuery, разделенная запятыми, на карту объекта
  • 0Как добавить расширяемый блок дополнительной информации в строку таблицы, созданную в выражении Angular repeat?
  • 1Проблема безопасности JavaScript
  • 1Могу ли я воссоздать исходный код и файлы решения для веб-сайта ASP.NET?
  • 0условно в зависимости от стиля
  • 1Как отключить захват событий окна в Emscripten + SDL?
  • 0Используя генератор FB «Мне нравится», я не могу заставить его работать на моей веб-странице.
  • 1Использование GreedyConstructorQuery и AutoMoqCustomization действительно использует жадный конструктор и вводит зависимость
  • 1преобразование моего длинного заявления в понимание списка
  • 0JQuery: как добавить CSS наведения с помощью JQuery CSS?
  • 1ANDROID: Как вы создаете сервлет Android
  • 1Неопределенная ошибка ссылки: AWS не определен
  • 1HTTPHandler против ASP.NET MVC FileStreamResult
  • 0Двойной нг-повторить сращивание, чтобы удалить элемент?
  • 1Каков наилучший способ отобразить данные таблицы соединений в сущности Java?
  • 1Как кратко нанести на карту самолет с NumPy
  • 1OneToMany JPA аннотация
  • 1Маршалинг структуры в одну строку строки
  • 1Измените рисование вкладок на выбор — Android
  • 1Python получает ключи JSON в качестве полного пути
  • 1C # Winform сохранить настройки
  • 1javascript ответ загрузки XMLHttpRequest после ответа сервера
  • 1Удалить элементы массива, которые появляются более одного раза

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Codeguard detected error in the program a log file will be created
  • Codeforces compilation error
  • Codeblocks как изменить шрифт
  • Codeblocks как изменить цвет фона
  • Codeblocks fatal error iostream no such file or directory