CodeIgniter - ¿cómo detectar errores de BD?


Hay una manera de hacer que CI lance una excepción {[4] } cuando encuentra un error DB en lugar de mostrar un mensaje como:

Se Ha Producido Un Error en La Base de Datos Número de Error: 1054 Unknown column ' foo ' in 'where clause' SELECT * FROM (FooBar) WHERE foo = '1'

NOTA: Solo quiero que esto suceda en un controlador. En los otros controladores, estoy feliz de que muestre los mensajes de error DB.

Author: Hamza Zafeer, 2011-10-21

10 answers

Pruebe estas funciones CI

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)
 51
Author: Oskenso Kashi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-21 04:22:12

Tal vez esto:

$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
 30
Author: RayJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-18 06:15:06

En Codeigniter 3.0 (CI3), todo lo que tienes que hacer es $this->db->error()

Si necesita obtener el último error que ha ocurrido, el método error() devolverá un array que contiene su código y mensaje

Http://www.codeigniter.com/user_guide/database/queries.html#handling-errors

 23
Author: CodeGodie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-13 23:32:56

Debe desactivar debug for database en config/database.php ->

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

Es mejor para la seguridad de su sitio web.

 14
Author: Kabir Hossain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-12 10:48:16

Sé que este hilo es viejo, pero por si acaso hay alguien más teniendo este problema. Este es un truco que usé sin tocar las clases de CI db. Deje su depuración activada y en su archivo de vista de errores, lance una excepción.

Así que en tu configuración de db, tienes:

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

Luego, en su archivo de vista de error de db, el mío está en application/errors/error_db.php reemplace todo el contenido con lo siguiente:

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

?>

Dado que se llamará al archivo de vista, el error siempre se lanzará como una excepción, puede agregar más tarde diferentes vistas para diferentes entornos.

 10
Author: tlogbon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-19 12:47:21

He creado una biblioteca simple para eso:

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

}

La consulta de ejemplo:

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

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

Y puedo atraparlo de esta manera en mi controlador:

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

 }
 4
Author: da1lbi3,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-27 18:23:32

Úsalo

    $this->db->_error_message(); 

Es mejor para encontrar errores.Después de completar su sitio. Cerrar los mensajes de error usándolo

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

Lo cambiará en la base de datos de su carpeta de configuración.php

 2
Author: Kabir Hossain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-26 11:24:14

Ponga este código en un archivo llamado MY_Exceptions.php en la carpeta 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
{

}

Hará que todos los errores de Encendido de código sean tratados como Excepción (CiError). Luego, activa toda la depuración de tu base de datos:

$db['default']['db_debug'] = true;
 2
Author: Adriano Gonçalves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-29 14:19:23

Si se utiliza DOP, adicional a todas las respuestas anteriores.

Registro mis errores silenciosamente como se muestra a continuación

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

        }
 0
Author: blumanski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-25 01:56:54

Desactivar la depuración de errores.

    $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;
    }
 0
Author: the_martux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-25 11:26:53