Automate queries with PHP ‘MagicQuery’ Class

MagicQuery is a PHP class that can automate the task of writing INSERT and UPDATE database queries. This is so simple that if you make an HTML form, MagicQuery can write and execute the query for you in just three lines of code no matter how long your form is. Such a class can play down both coding time and chance of errors in the query, because everything in here is pre-tested and automated.

Lets go with an example and see why MagicQuery is called so.

Take a simple form as shown above. Clicking on the ADD button submits the form to execute the INSERT query on a database table, say ‘address_table’. Now think if the same form has over 50 textboxes. You sit down to prepare the insert query and spend hours writing and testing it before everything is brought under control.

MagicQuery can bypass the task with one simple rule. Just that, the name of the form field should be kept same as the name of the corresponding field in the database table. Refering the above form, if the database field-name is ‘name’, the HTML form field name attribute should be name=”name”. The MagicQuery function fetchForm() can automatically fetch up values from $_REQUERT global array variable and prepare the query all by itself.

Lets see the three lines of code needed to handle the action and execute the query.

1) The first line is of course instantiating the MagicQuery class.

$query = new MagicQuery( ‘address_table’ ); Note that, database table name is passed when creating the object.

2) Fetching values from form is the next step.

$query->fetchForm(); However arguments like, $query->fetchForm( $_POST ) and $query->fetchForm( $_GET ) can also be passed, which tells the function to depend on the passed argument to make query.

3) The query is now ready and you just need to run it.

$query->run(); But before you go for the actual run, MagicQuery lets you to see your query (with some visual formattings). Just put the code $query->printQuery() instead of $query->run() and see how the query is printed on the top of the page.

Feel free to download the example below and try it out yourself. I’ve used this class to build a few sites and found it to be very effective and time saving. Hope you’ll feel the same.




Get in Touch

Get In Touch - Special pages