UPDATED: There is an issue whereby this code does not work as expected with MySQL. As a result, the concept has been reworked and listed under the entry "Consolidated query executions version 2."
In an effort to adhere to the DRY principle, or don't repeat yourself, the routine defined in this piece can be added to programs that employ a series of queries. The idea is that it moves a few lines of code that would otherwise need to be in each method or function that calls a query to a database server.
This snippet is coded with PHP and represents a method from a larger class. There are more details about the code itself in the comments of the code.
As a note about this particular implementation, the TRY/CATCH block is an attempt to gracefully handle the results the PHP PDO database interface depending on the type of query that was run. That's to say, a SELECT instead of an UPDATE, INSERT, or DELETE. The second catch block will try to catch any actual problems with running the query.
In an effort to adhere to the DRY principle, or don't repeat yourself, the routine defined in this piece can be added to programs that employ a series of queries. The idea is that it moves a few lines of code that would otherwise need to be in each method or function that calls a query to a database server.
This snippet is coded with PHP and represents a method from a larger class. There are more details about the code itself in the comments of the code.
What happens is that the typical lines to actually invoke the query and then collect the results have been moved to this method. Using this consolidated approach a few lines have been reduced to one.private function run($sql) { // Assumes $this->Conn has been set up in advance as a PDO connection. $Query = $this->Conn->prepare($sql); if((func_num_args() == 2) && is_array(func_get_arg(1))) { $Query->execute(func_get_arg(1)); } else { $Query->execute(array()); } // Assuming a SELECT query. try { // Returns ARRAY return $Query->fetchAll(\PDO::FETCH_ASSOC); } // Otherwise, it's likely an UPDATE, INSERT, or DELETE. catch(\PDOException $e) { // Returns INTEGER return $Query->rowCount(); } // Caught some other error. catch(\PDOException $e) { return $e->getMessage(); } }
As a note about this particular implementation, the TRY/CATCH block is an attempt to gracefully handle the results the PHP PDO database interface depending on the type of query that was run. That's to say, a SELECT instead of an UPDATE, INSERT, or DELETE. The second catch block will try to catch any actual problems with running the query.
Comments
Post a Comment