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.
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
New in version 4.3.0.
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
New in version 4.3.0.
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.
Can someone help me?
I am a beginner and trying to make wearing CodeIgniter authentication, but when I try to make an error like this
A Database Error Occurred
Error Number: 1046
No database selected
SELECT * FROM (`user`) WHERE `user_username` = 'amanda' AND user_passwordMD5("12345") =
Filename: C:xampphtdocscodeignitersystemdatabaseDB_driver.php
Line Number: 330
thanx
asked Apr 5, 2014 at 6:05
4
please make sure you have setup database configuration in application/config/database.php file
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'my_database';
answered Apr 5, 2014 at 6:10
3
Check the database.php file in application/config/
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'mypassword';
$db['default']['database'] = 'my_database'; // here is the database selection
answered Apr 5, 2014 at 6:12
ReNiSh ARReNiSh AR
2,7822 gold badges30 silver badges42 bronze badges
3
Open the file application/config/database.php
file and change the following line:
$db['default']['dbdriver'] = 'mysql';
To:
$db['default']['dbdriver'] = 'mysqli';
This shift to mysqli
saved by day.
martianwars
6,3605 gold badges34 silver badges44 bronze badges
answered Dec 10, 2016 at 18:50
Lost connection to MySQL server during query
Line Number: 337
answered Jul 6, 2017 at 7:16
people who critic here should have not only education but also common sense. they should know also what time I made this comment and what was my reputation score. It is not only about giving an answer but the giving also the suggestion a beginner can pin-point the problem. I could have given the answer but just after posting my comment someone already given answer. Look below — best among anyone given here
$config['hostname'] = "localhost";
$config['username'] = "username";
$config['password'] = "password";
$config['database'] = "database";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
answered Apr 5, 2014 at 14:53
user3470953user3470953
11k2 gold badges17 silver badges18 bronze badges
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 :
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:
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»;