Considering the limitations of traditional plain MySQL driver, we seek a solution for creating an insert/update helper function that utilizes PDO prepared statements' features.
Prepared Statement Helper Function
function dbSet($fields, & $values) { $set = ''; $values = array(); foreach ($fields as $field) { if (isset($_POST[$field])) { $set .= "`$field` = ?,"; $values[] = $_POST[$field]; } } return rtrim($set, ','); }
Usage
$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>
This helper function provides a straightforward approach to insert data using PDO prepared statements. It reduces code repetition and promotes security by eliminating the need for direct string concatenation.
Alternate Solution: Object-Relational Mapping (ORM)
For a more comprehensive solution, consider using an ORM like Doctrine. This approach provides an intuitive interface for managing database entities, allowing you to perform operations like saving data with minimal code:
$table = new Table(); $table->fromArray($_POST); $table->save();
By incorporating the ORM solution, you can streamline your database operations and enforce data validation within your model.
The above is the detailed content of How Can I Create a Secure Insert/Update Helper Function Using PDO Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!