I have a very simple helper function to produce SET statement for traditional plain mysql driver usage:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
used like this
$id = intval($_POST['id']);
$fields = explode(" ","name surname lastname address zip fax phone");
$_POST['date'] = $_POST['y']."-".$_POST['m']."-".$_POST['d'];
$query = "UPDATE $table SET ".dbSet($fields)." stamp=NOW() WHERE id=$id";
it makes code quite DRY and easy but flexible at the same time.
I gotta ask if anyone willing to share a similar function, utilizing PDO prepared statements feature?
I am still in doubts, how to accomplish this.
Is there a straight and simple way to use PDO prepared statements to insert data?
What form it should be? Query builder helper? Or insert query helper? What parameters it should take?
I hope it can be easy enough to be used as an answer here on SO. Because in the every topic we can see prepared statements usage recommendation, but there is not a single good example. Real life example, I mean. To type bind_param() 20 times is not a good programming style I believe. And even 20 question marks too.
Reference: How can I prevent SQL injection in PHP?
Just in addition to other answers: a method for proper quote of column names:
You can extend PDO like that:
I've been patching something trivial together for what I consider recurring parameter binding cases. http://fossil.include-once.org/hybrid7/wiki/db
Anyway; it provides some alternative prepared statement placeholders. Your example could be shortened into:
This case only works with named parameters, so $set would be array("name"=>..) and $where=array("id"=>123). The
:,
gets expanded on the first array you pass. It's replaced with comma-separated name=:name pairs (that's why its mnemonic is:,
).There are a few more placeholders
:,
:&
::
and:?
for different use cases. Only the??
is really somewhat of a standard. So it needs some getting used to, but it significantly simplifies prepared statements and array binding (which PDO doesn't do natively).Here's my general database abstraction class. Take a look at the
autoExecute()
function. It offers tons of flexibility for whatever it is you might want to accomplish. I should warn that this was written for PHP 5.3, and has been slightly tailored for PostgreSQL.