DB / autoprepare() ?

From: Date: Tue, 04 Jun 2002 11:52:13 +0000
Subject: DB / autoprepare() ?
Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-6730@lists.php.net to get a copy of this message
Hello, One thing I feel borring is to write my sql queries to insert or update records in database. Like : INSERT INTO table (field1, field2, field3, ...) VALUES (value1, value2, value3, ...) DB / prepare() is really a good idea because you need only to write : INSERT INTO table (field1, field2, field3, ...) VALUES (?, ?, ?...) But, if you want to change the structure of the table or the number of the fields, you have to modify the query. So I think it would be to have a autoprepare() method which would take an array and would automaticaly deal with it. Like : $array = array( 'field1' -> value1, 'field2' -> value2, 'field3' -> value3, 'field4' -> value4, 'field5' -> value5, (...) ); the method will write the query : INSERT INTO table (field1, field2, field3, ...) VALUES (?, ?, ?...) So, no query to write or to change if we modify fields names... For that, it would be a method like (non tested) : // it's an example for INSERT queries only. function insert_autoPrepare($table, $array) { $values = ''; $names = ''; $first = true; while (list($key, $value) = each($array)) { if ($first) { $first = false; } else { $names.=','; $values.=','; } $names.= $key; $values.= '?'; } return "INSERT INTO $table ($names) VALUES ($values)"; } Or something like it. The final method has to make INSERT and UPDATE queries and have to call prepare() instead of returning the query... NB : I use only keys of the assoc. But values will be used by execute() What do you think about this idea ? Any opposite opinions, remarks or questions are welcome. Thanks, Fabien

« previous php.pear.dev (#6730) next »