Database Error Handling In Codeigniter
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of codeigniter active record error handling this site About Us Learn more about Stack Overflow the company Business Learn
Codeigniter Query Error Handling
more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question codeigniter try catch x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up CodeIgniter
Codeigniter Get Mysql Error
- how to catch DB errors? up vote 36 down vote favorite 6 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`) WHERE `foo` = '1' NOTE: I only want this to happen codeigniter insert error-handling in one controller. In the other controllers, I'm happy for it to display the DB error messages. php codeigniter share|improve this question edited Oct 20 '11 at 23:29 asked Oct 20 '11 at 23:22 StackOverflowNewbie 9,96467186337 add a comment| 7 Answers 7 active oldest votes up vote 34 down vote accepted Try these CI functions $this->db->_error_message(); (mysql_error equivalent) $this->db->_error_number(); (mysql_errno equivalent) share|improve this answer edited Oct 21 '11 at 4:22 answered Oct 21 '11 at 4:17 Oskenso Kashi 51147 3 And when the queries are dinamically created, $this->db->last_query() useful too. –uzsolt Oct 21 '11 at 15:17 5 How do these prevent the messages from displaying? –StackOverflowNewbie Oct 21 '11 at 21:36 7 You must turn debug off for database in config/database.php -> $db['default']['db_debug'] = FALSE; –decebal Dec 12 '12 at 12:47 8 Why is not possible to use Exception instead :-( ? –Thomas Decaux Mar 8 '13 at 11:39 16 These methods have been removed in CodeIgniter version 3. Use $this->db->error() instead. (see codeigniter.com/user_guide/database/…) –mxgr Jul 26 '15 at 11:17 | show 2 more comments up vote 15 down vote Maybe this: $db_debug =
Chart Model-View-Controller Architectural Goals Tutorial Static pages News section Create news items Conclusion Contributing to CodeIgniter Writing CodeIgniter Documentation Developer's Certificate of Origin 1.1 General
Codeigniter Error Handling
Topics CodeIgniter URLs Controllers Reserved Names Views Models Helpers Using
Call To Undefined Method Ci_db_mysql_driver::_error_message()
CodeIgniter Libraries Creating Libraries Using CodeIgniter Drivers Creating Drivers Creating Core System Classes Creating Ancillary codeigniter $this- db- error_number () Classes Hooks - Extending the Framework Core Auto-loading Resources Common Functions Compatibility Functions URI Routing Error Handling Caching Profiling Your Application Running via the CLI Managing http://stackoverflow.com/questions/7843406/codeigniter-how-to-catch-db-errors your Applications Handling Multiple Environments Alternate PHP Syntax for View Files Security PHP Style Guide Libraries Benchmarking Class Caching Driver Calendaring Class Shopping Cart Class Config Class Email Class Encrypt Class Encryption Library File Uploading Class Form Validation FTP Class Image Manipulation Class Input Class Javascript Class Language Class Loader Class https://www.codeigniter.com/userguide3/database/queries.html Migrations Class Output Class Pagination Class Template Parser Class Security Class Session Library HTML Table Class Trackback Class Typography Class Unit Testing Class URI Class User Agent Class XML-RPC and XML-RPC Server Classes Zip Encoding Class Database Reference Quick Start: Usage Examples Database Configuration Connecting to a Database Running Queries Generating Query Results Query Helper Functions Query Builder Class Transactions Getting MetaData Custom Function Calls Query Caching Database Manipulation with Database Forge Database Utilities Class Database Driver Reference Helpers Array Helper CAPTCHA Helper Cookie Helper Date Helper Directory Helper Download Helper Email Helper File Helper Form Helper HTML Helper Inflector Helper Language Helper Number Helper Path Helper Security Helper Smiley Helper String Helper Text Helper Typography Helper URL Helper XML Helper CodeIgniter Welcome to CodeIgniter Installation Instructions Downloading CodeIgniter Installation Instructions Upgrading From a Previous Version Troubleshooting CodeIgniter Overview Getting Started CodeIgniter at a Glance Supported Features Application Flow Chart Model-View-Controller
View the full version with proper formatting. El Forum01-22-2014, 07:34 AM [eluser]Andrewkha[/eluser] Hi! I have a DB using foreign keys with restrict on delete settings. So if I delete from the DB the record which is not http://forum.codeigniter.com/archive/index.php?thread-60134.html used by other tables, everything is OK. But if I try to delete a http://thesimplesynthesis.com/article/codeigniter record that is tied to records in other tables (using a foreign key), my web application shows the error: Code: A Database Error Occurred
Error Number: 1451
Cannot delete or update a parent row: a foreign key constraint fails (`cms`.`cm_photos`, CONSTRAINT `photoid` FOREIGN KEY (`cat`) REFERENCES `cm_photo_cat` (`id`) ON UPDATE error handling CASCADE)
DELETE FROM `cm_photo_cat` WHERE `id` IN ('2')
Filename: Z:\home\cms\www\system\database\DB_driver.php Line Number: 330 How can I capture this in my code? I use the following commands: Code: $this->db->where_in($this->idkey, $id);
$this->db->delete($this->table) Making smth like this Code: if(!$this->db->delete($this->table)) doesn't work. Any ideas? El Forum01-22-2014, 09:40 AM [eluser]jonez[/eluser] It depends on how the action is run. If it's a normal page change you could try/catch database error handling the delete and handle the error gracefully, or if it's an AJAX call you can catch the error event and alert the user. El Forum01-22-2014, 11:12 AM [eluser]Andrewkha[/eluser] Hi Thanks for your response. However the question is which condition should I check in the try/catch statement? When the exception should be thrown? If I do smth like try if(!$this->db->delete($this->table)) { throw new Exception()} catch (...) it doesn't generate any exception. Just get the error as in my initial post... El Forum01-22-2014, 12:31 PM [eluser]CroNiX[/eluser] I believe you need to turn db_debug to FALSE in order to bypass CI's automatic db error handling. Otherwise it will use CI's exception class to handle them before you get a chance to. However, I don't think the db class throws its own exceptions, so you need to test the result of the query and manually grab the error. It's been awhile since I attempted this but you can try something like Code: if ( ! $this->db->delete($this->table))
{
$msg = $this->db->_error_message();
$num = $this->db->_error_number();
} All db methods return TRUE upon success. El Forum01-22-2014, 02:13 PM [eluser]jonez[/eluser] [quote author="Andrewkha" date="1390410732"]Hi Thanks for your response. However the question is which condition should I check in the try/catch statement? When
and directory structure. It doesn't even autoload the database library. It's flexible enough that controllers don't even need models or views, and models have almost all the functionality of controllers. Autoloading Classes You can autoload classes by adding this little script to application/config/config.php: // deduce the application root from this file's location function __autoload ($class) { global $config; // ignore autoloading CodeIgniter classes $prefix = substr($class,0,2); if ($prefix!='CI' && $prefix!=$config['subclass_prefix']) { include(str_replace('_', DIRECTORY_SEPARATOR, strtolower($class)) . '.php'); } } // set the root of the application directory define('APP_ROOT', dirname(dirname(dirname(__FILE__)))); // put most likely paths first set_include_path('.' . PATH_SEPARATOR . APP_ROOT . '/application/libraries' . PATH_SEPARATOR . APP_ROOT . '/application/models' . PATH_SEPARATOR . APP_ROOT . '/application/controllers' . PATH_SEPARATOR . get_include_path() ); I have to credit the technique from Gerard Sychay's Pox Framework. The __autoload function is like a magic method in that when a class is not found, the name of the class being looked for is sent as a parameter and the function is given the option of finding the file that has the class. Finally, to expand the scope of directories the autoload function has to look in we add the library, model, and controller folders to PHP's include path using set_include_path. Now, three quick things to note about what the autoload function is doing: Classes beginning with 'CI' and the 'subclass_prefix' are ignored because we don't want to mess with the core of CodeIgniter The class name is changed to lowercase because lowercase filenames are CodeIgniter's convention A class name of 'Post_Comment' will be looked for in the following locations: application/libraries/post/comment.php application/models/post/comment.php application/controllers/post/comment.php (and any in any other include path) Using this technique allows you do things like: class User extends MyModel Where MyModel is in applicatio