PDO Prepared Statements for Insert/Update Helper Function
In traditional MySQL driver scenarios, the dbSet() function is a valuable tool for generating SET statements. However, when utilizing PDO prepared statements, a similar approach is needed to maintain code dryness and flexibility.
PDO Prepared Statement Helper Function
The following helper function, dbSet(), can be utilized to achieve this:
function dbSet($fields, &$values) { $set = ''; $values = array(); foreach ($fields as $field) { if (isset($_POST[$field])) { $set .= "`$field` = ?,"; $values[] = $_POST[$field]; } } return rtrim($set, ','); }
Usage
Consider the following example:
$fields = explode(" ","name surname lastname address zip fax phone date"); $_POST['date'] = $_POST['y']."-".$_POST['m']."-"$_POST['d']; $query = "UPDATE $table SET ".dbSet($fields, $values).", stamp=NOW() WHERE>
ORM Alternative
For a more comprehensive solution, consider employing an ORM (object-relational mapping) framework such as Doctrine. With ORM, data population can be simplified considerably:
$table = new Table(); $table->fromArray($_POST); $table->save();
PDO Extension Class
For a customized solution, creating a PDO extension class can provide a convenient way to handle prepared statement queries efficiently, reducing the need for verbose bind_param() calls.
The above is the detailed content of How Can I Create a PDO Prepared Statement Helper Function for Insert/Update Operations?. For more information, please follow other related articles on the PHP Chinese website!