HomeMySQL Dynamically Insert and Update Values In a MySQL Database Using OOP
Dynamically Insert and Update Values In a MySQL Database Using OOP
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.
So you have a new project. It requires simple add, edit, and delete actions. Simple enough, but think of all the time you spend writing simple, time-consuming insert and update SQL statements, and praying to God that you didn't mess up the column sequence, forget a comma, or make some other silly type-o that you spend precious coding time looking for and correcting.
Think of the following: in a 25 or 50 field form, you have 50 or 100 pieces of data to enter into the SQL statement:
mysql_query
("INSERT INTO myTBL (col1,col2,col3,…col30,col31) VALUES ('".$val1."', '".$val2."', '".$val3."', …'".$is_this_val30."', '".$please_be_val31."'");
It's confusing, and it makes your code look and feel like crap. It gets even worse when you have to add or delete a field, then you have to go through the SQL again and find that one column amidst the sea of endless columns and then go find that darned variable in that myriad of weird names you made up. Argh! I can hear your frustrations now. Well there is a solution to our long-SQL-statement-woes. 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.