HomeMySQL Page 7 - Dynamically Insert and Update Values In a MySQL Database Using OOP
You Wouldn't Have to Update It Had You Gotten It Right the First Time - MySQL
Stop writing insert and update SQL statements and cut the time you spend writing simple SQL in half while focusing on the more complicated things. Leave it up to OOP to help you out. We will make a class that goes out and looks for the values for us and builds a SQL statement on the fly. All we have to do is make sure the column names in the database correspond with the field names in the HTML form. Believe me when I say it saves TONS of time. I never write applications that don't use it.
// Include the file that contains // the MyDatabase class require('database.class.php');
// If the form was submitted... if($_POST['id']) { // Instantiate the class $SQL = new MyDatabase; // Connect to the database $SQL->Connect();
// Update values in my_tbl // where id = $_POST['id'] if(!$SQL->UpdateDB('my_tbl', $_POST['id'], 'id')) die( $SQL->GetError() );
// Disconnect from the database $SQL->Disconnect(); }
Look familiar? It should, unless you accidentally / intentionally skipped a section or two. The only difference now is we are using the UpdateDB method to update our table and now we are passing the id and the name of the id column in the database table.
You Are Much Faster Now, Grasshopper
Now you are able to focus, grasshopper. No more annoying insert and update statements to distract you. This class has become a permanent "must have" in my arsenal of includes. It's like an audio stream from Digitally Imported Radio (www.di.fm) - I never code without it.
So there you have it; my 2 dollars. It is my hope that you will find this class as helpful as I have. Just don't use it in a production environment without adding some more validation and better error reporting and so on. Until next time!