Codeigniter - handling errors when using active record - php

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;

Related

Laravel and multiple database connections

This might be a silly question. I have two separate databases that are being used with Laravel 4. One of them can only be accessed with a certain IP (security reasons) while the other can be accessed. I have two different mysql connections. I have seen the Database connection test using this:
if(DB::connection('mysql')->getDatabaseName()){ }
To test what can be seen and what can't be seen, I tried to give the mysql a false password. I get this nice ugly error how it can't connect. Is there a way to make it where if the Database cannot be reached, just to ignore it? There's only one PHP class that's calling the secure only database on page load, but the above check doesn't seem to be working.
Going through the core code of laravel, there is no specific exceptions being thrown when a database connection fails.
The solution hence, is:
try {
//Strings always evaluate to boolean true
$dbConnected = (bool)DB::connection('mysql')->getDatabaseName();
}
catch (Exception $e)
{
$dbConnected = false;
}
Then work your code based on the variable $dbConnected.

How to catch DB errors in CodeIgniter 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>';

When is error checking too much?

During the process of my PHP learning I have been trying to read up on the best practices for error reporting and handling, but statements vary person to person and I have struggled to come up with a clear concise way of handling errors in my applications. I use exceptions on things that could go wrong, but for the most part it is hard for me to understand whether an exception should kill the application and display an error page or just be caught and silently dealt with.
Something that seems to elude me is, is there such thing as too much reporting? Every single time you call a function something could go horribly wrong meaning that if you were to confirm every single function call you would have to fill pages with if statements and work out what effect one failure may have on the rest. Is there a concise document or idea for error reporting that could clear this up for me? Are there best practices? What are the best examples of good error handling?
Currently I do the following:
Add important event results to an array to be logged and emailed to me if a fatal error was to occur
Display abstract/generic errors for fatal errors.
Use exceptions for cases that are likely to fail
Turn on error reporting in a development environment and off for live environment
Validate all user input data
Sanitizing invalid user input
Display concise, informative error messages to users without providing a platform for exploitation.
Exceptions are the only thing that you haven't understood IMHO: exceptions are meant to be out of your control, are meant to be caught be dealt with from outside the scope they are thrown in. The try block has a specific limit: it should contain related actions. For example take a database try catch block:
$array = array();
try {
// connect throws exception on fail
// query throws exception on fail
// fetch results into $array
} catch (...) {
$array[0]['default'] = 'me';
$array[0]['default2'] = ...;
...
}
as you can see I put every database related function inside the try block. If the connection fails the query and the fetching is not performed because they would have no sense without a connection. If the querying fails the fetching is skipped because there would be no sense in fetching no results. And if anything goes wrong, I have an empty $array to deal with: so I can, for example, populate it with default data.
Using exceptions like:
$array = array();
try {
if (!file_exists('file.php')) throw new Exception('file does not exists');
include('file.php');
} catch (Exception $e) {
trigger_error($e->getMessage());
}
makes no sense. It just a longer version of:
if (!file_exists('file.php')) trigger_error('file does not exists');
include('file.php');

Is it possible to configure MySQL logging so that it only reports queries that were rolled back?

I have an intermittent bug that I'm trying to track down, and I'd like to capture only MySQL queries that fail resulting in a rollback. I don't want a full general query or binary log because there would be millions of entries in the haystack to sort through.
Something like this solution except for MySQL would be perfect.
TIA,
JD
Not a direct answer to your question, but the utility mysqlbinlog can extract data from the binary log.
See: the user comments in this page: http://dev.mysql.com/doc/refman/5.5/en/binary-log.html
And this page: http://ronaldbradford.com/blog/mysql-dml-stats-per-table-2009-09-09/
Here's the official documentation for mysqlbinlog, which might help you get the info you need.
In MySQL it is very difficult (or maybe impossible). You can do it in PHP. If you don't use low functions like mysql_query and you use high methods like ->query(), you can add logic to theirs. If query failed (return false for example), add it to log. Sorry for my english.
Note for Zend_DB:
class My_DB extends Zend_DB {
public function insert($data) {
try {
parent::insert($data);
} catch (Exception $e) {
// put $e->getMessage() to log
}
}
}
You can overwrite different methods, such as update, query and others...

PHP: MySQL error hook?

I've been developing a web application with PHP and MySQL. The other day, I made some changes to the database and adapted one page to the new table layout but not another page. I didn't test well enough, so the site went online with the error still in the other page. It was a simple MySQL error, and once one of my co-workers spotted it, it was a simple fix.
Now that it's happened, I'd like to know how I can catch other MySQL errors. I'm thinking about some sort of notification system, that would send me an email when a mysql_query() fails.
I understand, of course, that I wouldn't be notified until after the error occurred, but at least I would have been notified immediately, rather than my co-worker come tell me after who-knows-how-many other people had run into the same fatal error.
Is there some sort of way to put in a hook, so that PHP automatically runs a function when an error happens? Or do I need to go through my code and add this functionality to every location where I use mysql_query()?
If the latter, do you have any recommendations on how to prevent something like this in the future? If this is the case I'll probably create a class to abstract SQL operations. I know I should have been doing this the whole time... But I did organize my sets of functions into different include files, so at least I'm doing most things right. Right?
You could use a wrapper function like this:
function mysql_query_wrapper($query, $link=null)
{
if (is_null($link)) {
$result = myql_query($query);
} else {
$result = myql_query($query, $link);
}
if (mysql_error($result)) {
// error occurred
}
return $result;
}
Then you just need to replace each mysql_query call with mysql_query_wrapper.
You can use custom functions for error handling using set_error_handler().
However, mysql_query won't trigger an error, but return false. The errors turn up only afterwards when trying to work with the results. In this case it might be better to define a custom wrapper function that calls mysql_query() and outputs possible errors using mysql_error(). That way, you can immediately halt your application on an error if so desired.

Categories