How to catch DB errors in CodeIgniter PHP - php

I am new to CodeIgniter, PHP and MySQL. I want to handle the DB generated errors. From one of the post in Stackoverflow, I knew that by following statement one can catch the error.
$this->db->_error_message();
But I cannot figure out the exact syntax of using that. Suppose I want to update the records of table named "table_name" by the following statement:
$array['rank']="8";
$array['class']="XII";
$this->db->where('roll_no',$roll_no);
$this->db->update("table_name", $array);
Here in the above code I want to catch the DB error whenever any DB level violation occurs i.e. either field name is not valid or some unique constraint violation occurs. If anyone helps me to fix that I would be really grateful. Thank you.

You can debug the database error on database configuration in (config/database.php) like this:
$db['default']['db_debug'] = TRUE;
More info read here
Also you can use Profiler to see all the queries and their speed. In controller you can put this:
$this->output->enable_profiler(TRUE);
More information read here

codeIgniter has functions for it
$this->db->_error_message();
$this->db->_error_number();
if(!$this->db->update("table_name", $array))
{
$this->db->_error_message();
$this->db->_error_number();
}

On Codeigniter version 2,
$this->db->_error_message();
$this->db->_error_number();
On Codeigniter version 3,
$db_error = $this->db->error();
echo '<pre>';print_r($db_error);echo '</pre>';

Related

How To Catch Exception DB::unprepared()

I want to run SQL script file in Laravel 5.5 and I use DB::unprepared($sql) which is good so far. But I found that DB::unprepared($sql) seems didn't return any error Exception. I try with different method but still didn't work.
Here some Exception class that I tried: \Exception, PDOException, \Illuminate\Database\QueryException, but didn't work.
Try tried get bolean return from DP::unprepared($sql) by doing this $return = DB::unprepared($sql); var_dump($return); but always return TRUE
I tried using DB::statement($sql), but it looks like use only for executing statement per statement. I need to run a whole sql file without any modification.
Could anyone help me how to catch any SQL script error? Any laravel function method that could help me catch SQL exception?
#Kenjiro, I'm sure you already solved your problem, one a half year past. But, if I nailed it, please mark my answer as it will help fellows with the same problem in the future. This post was the first when googling and it has no answer...
Well, it seems that, like me, you were submiting a multistatement query to DB::unprepared.
Say:
$sql = '
drop temporary table if exists tmp_data;
create temporary table tmp_data
select1 *
from data;'
$result = DB::unprepared($sql)
Even with the typo in select1, the code will run and $result will be true.
To make it work as expected we have to submit each single statement:
$sql = 'drop temporary table if exists tmp_data;'
DB::unprepared($sql);
$sql = '
create temporary table tmp_data
select1 *
from data;'
DB::unprepared($sql)
No need to check the result. The second call to unprepared will raise an exception.
That's it.
You can check it with try catch :
try {
//your code
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
// Note any method of class PDOException can be called on $ex.
}
Also check For Reference : Check This out

How to retrieve the result of a Firebird INSERT ... RETURNING in Yii

I am trying to use Firebird 2.1 with Yii (using plugin http://www.yiiframework.com/extension/yii2-firebird/) but I have problems doing insert (save) commands, the error message is:
SQLSTATE[HY000]: General error: -502 Cursor is not open
I have found that Yii generates insert statement with returning clause, e.g.:
INSERT INTO CONTRACTS (contract_no) VALUES (10002) RETURNING contract_no
And I guess that the problem is the following: Yii tries to read results from this insert command but there are problems with Yii-Firebird plugin which closes cursors immediately after pdoStatement->execute. The exception is generated in yii/db/Command.php file function protected function queryInternal($method, $fetchMode = null) whose code reads:
$this->pdoStatement->execute();
if ($method === '') {
$result = new DataReader($this);
} else {
if ($fetchMode === null) {
$fetchMode = $this->fetchMode;
}
try {
$result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
$this->pdoStatement->closeCursor();
} catch (Exception $ex) {
Yii::trace('Fetch error', 'yii\db\Command::query');
}
}
I have the following questions:
Does anyone uses Firebird with Yii, what the experience is?
How to explain code:
call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
and where to correct it? I guess that this method should be overriden in Yii-Firebird plugin with the aim to check whether the cursor is open and, if necessary, open the cursor?
Answer for the first question.
With the YII2 I use "edgardmessias/yii2-firebird": "^0.7.1", extension for Firebird 2.1.1883.
I found that it better to work not with ActiveDataProvider, but with
$dataProvider = new ArrayDataProvider([
in the SearchModel. That way are not so much errors while searching with relation.
But main problem is case sensitive search. I always needed to write in the search field same letters what record have, Big or small.

Laravel handle nested exceptions and keep going

I have a question regarding PHP's way to handle exceptions and Laravel 5.
Here's a snippet of what I'm trying to accomplish
try
{
//set up webservices
saveData();
} catch(exception $e)
{
Log:error('stuff went bananas')
}
saveData(){
//record stuff through DB with eloquent
//in case some data is missing connect to a second DB
try
{
connect()
query to get data
}catch(exception $e)
{
//log error again
}
In other words, I'm calling webservices that receive data. I'm then inserting these into my own DB inside the Model.
At this stage I'm trying to see if I know the user ID that I just received. In case I don't I have to connect to a second database to request that same user.
There are two issues though
the second database I'm trying to connect isn't likely to be up
it will often not hold the information I need (I have to try again the next day)
There's nothing I can do against these issues. But what I want is for my code to try and connect, and in case it fails, log the errors and keep moving inserting the data.
Thanks in advance.

Zend Framework mysql query return server 500 error

I use Zend Framework. Code
$this->_db->query("INSERT INTO blog SET ....")
returns 500 error. But if I replace it to
mysql_query("INSERT INTO blog SET ....")
all ok. What can be wrong?
Are you sure $this->_db is what you expect it to be?
If you're using the default ErrorController, setting
resources.frontController.params.displayExceptions = 1
in your /application/config/application.ini should give you a backtrace of the error.
Also, if it really is just the query generating an exception you can wrap it in a try/catch and see the exception.
try {
$this->_db->query("INSERT INTO blog SET ....");
} catch(Exception $e) {
echo $e->getMessage();
}
I think your SQL syntax is wrong. Correct syntax:
INSERT INTO table (fields) VALUES (values)
EDIT: Oh sorry just read that your mysql_query() is working with the same SQL. As someone else recommended I'd recommend checking the logs.
Most certainly your $this->_db is not an instance of Zend_Db_Adapter_Abstract :) Even more it may be NULL ;)
I had the same issue with a select statement in Zend. Simply adding a try..catch block around the $this->fetchRow($select) line solved the issue. Curiously, there were no exceptions caught..!!

Codeigniter - handling errors when using active record

I am putting together a few models for my codeigniter site and can't seem to find any word in the documentation of how to handle errors that could occur when using the Active Record system.
The documentation demonstrates how to perform CRUD along with some relatively involved queries but no where along the line is error handling discussed. I have done a quick google search and it would appear that the Active Record classes do not throw exceptions. Is this the case? No try catch then...
So, how do you code to handle database errors in codeigniter? (failed connection, duplicate key, broken referential integrity, truncation, bad data types etc etc)
Whether you're using the active record class or not, you can access database errors using $this->db->_error_message() and $this->db->_error_number().
If you're using a mysql database, these functions are equivalent to mysql_error() and mysql_errno() respectively. You can check out these functions by looking at the source code for the database driver for the database you're using. They're located in system/database/drivers.
So, after you run a query, you can check for errors using something like:
if ($this->db->_error_message()) \\handle error
Straight from the CodeIgniter support forum:
$res = $this->db->query($str);
if (!$res) {
// if query returns null
$msg = $this->db->_error_message();
$num = $this->db->_error_number();
$data['msg'] = "Error(".$num.") ".$msg;
$this->load->view('customers_edit_view',$data);
}
Note that you can also log Active Record errors by going into your CI app config file and setting the following:
$config['log_threshold'] = 1;

Categories