Codeigniter Database Insert Error
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 this site About Us Learn more about Stack Overflow the company Business codeigniter db insert Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation
Codeigniter Db Insert Return Value
Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like codeigniter active record error handling you, helping each other. Join them; it only takes a minute: Sign up Code Igniter catch errors on inserting data (Active Record) up vote 3 down vote favorite I am inserting data into my database using the codeigniter query error handling following code: $this->db->set('event_id', $event_id); ... $this->db->set('creator_id', $creator_id); $this->db->insert('event'); How can I make sure the process was successful and show the user a confirmation message, else an error message? php database activerecord error-handling codeigniter-2 share|improve this question asked Nov 20 '11 at 15:30 lodhb 4252618 1 what is the output of var_dump($this->db->insert('event')); ? –Shoe Nov 20 '11 at 16:07 add a comment| 1 Answer 1 active oldest votes up vote 5 down vote accepted Uhm,
Codeigniter Get Mysql Error
IIRC the method returns true if succesful, so you could go with a simple if($this->db->insert('event')) { echo 'Row succesfully inserted!'; } Otherwise, you might always count the affected rows: //.... $this->db->insert('event'); if($this->db->affected_rows() > 0) { echo 'row succesfully inserted'; } UPDATE after comment: I believe your three insert_batch() are on three different tables, so a check should be down on each one. Anyway, what's puzzling me is the reason behin this check..Query don't fail randomly: possibily they should never fail and when they do you'll know through errors (logged or dislayed). share|improve this answer edited Nov 21 '11 at 5:41 answered Nov 20 '11 at 16:25 Damien Pirsy 19.7k64264 I have two insert_batch($array) after that, do I have to test each insert before doing another? Or can I just test them all 3, i.e. if($this->db->insert('event') && $this->db->insert_batch($arr1) && $this->db->insert_batch($arr2)){...} –lodhb Nov 21 '11 at 3:26 @lodhb I updated my answer –Damien Pirsy Nov 21 '11 at 5:41 Worked, thanks! –lodhb Nov 23 '11 at 12:38 1 A much better technique, if you are using several different inserts to different tables would be to use a transaction. These can be rolled back if one or more of the database queries fails. For details, see ellislab.com/codeigniter/user-guide/database/transactions.html This will take all the effort out of "a check should be d
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 Topics CodeIgniter URLs Controllers Reserved Names codeigniter insert error-handling Views Models Helpers Using CodeIgniter Libraries Creating Libraries Using CodeIgniter Drivers codeigniter try catch Creating Drivers Creating Core System Classes Creating Ancillary Classes Hooks - Extending the Framework Core Auto-loading Resources Common
Codeigniter Error Handling
Functions Compatibility Functions URI Routing Error Handling Caching Profiling Your Application Running via the CLI Managing your Applications Handling Multiple Environments Alternate PHP Syntax for View Files Security http://stackoverflow.com/questions/8202547/code-igniter-catch-errors-on-inserting-data-active-record 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 Migrations Class Output Class Pagination Class Template Parser Class Security Class Session Library HTML Table Class Trackback Class https://www.codeigniter.com/userguide3/database/queries.html 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 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 Topics CodeIgniter URLs Controllers Reserved Names Views Models Helpers Using CodeIgniter Libraries Creating Librar
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 Topics CodeIgniter URLs Controllers Reserved Names Views https://www.codeigniter.com/user_guide/general/errors.html Models Helpers Using CodeIgniter Libraries Creating Libraries Using CodeIgniter Drivers Creating Drivers http://thesimplesynthesis.com/article/codeigniter Creating Core System Classes Creating Ancillary 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 your Applications Handling Multiple Environments Alternate PHP Syntax for View Files Security PHP Style error handling 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 Migrations Class Output Class Pagination Class Template Parser Class Security Class Session Library HTML Table Class Trackback Class Typography Class Unit codeigniter db insert 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 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 Topics CodeIgniter URLs Controllers Reserved Names Views Models Helpers Using CodeIgniter Libraries Creating Libraries Using CodeIgniter Drivers Creating Drivers
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 application/models/mymodel.php. Error Handling Handling Form Errors There are many ways to get form errors (see this StackOverflow thread and this one) including the built in form_errors function. The easiest way, I believe is to do the following: $validator =& _get_validation_object(); $error_messages = $validator->_error_array; Try-Catch Method Best Practices (Introduction) There is no de facto way to handle errors in CodeIgniter so I'm going to extrapolate what I think the best is. The best way is to throw and catch PHP exce