Reputation: 48465
I want to use PDO prepared statements but i find it really time consuming to type. it would be super useful if there is a function to just pass the following associative array:
array(
"title"=>$title
"userid"=>$userid
"post"=>$body
)
Keeping in mind that the keys in the array always match the rows in the SQL table. recaping everything, this should cut off the effort to type the :foo
and type them again in the execute function.
I'm specifically talking about the INSERT query.
How to do that?
Upvotes: 6
Views: 6187
Reputation: 4094
Slighly improved PDO Insert function that also takes security into consideration by preventing SQL Injection attacks:
// Insert an array with key-value pairs into a specified database table (MySQL).
function pdo_insert($dbh,$table,$keyvals) {
$sql = sprintf("INSERT INTO %s ( `%s` ) %sVALUES ( :%s );",
$table,
implode("`, `", array_keys($keyvals)),
PHP_EOL,
implode(", :", array_keys($keyvals))
);
$stmt = $dbh->prepare($sql);
foreach ($keyvals as $field => $value) {
$stmt->bindValue(":$field", $value, PDO::PARAM_STR);
}
$stmt->execute();
return $dbh->lastInsertId();
}
// Convert special characters to HTML safe entities.
function h($str) {
return trim(stripslashes(htmlspecialchars($str, ENT_QUOTES, 'utf-8')));
}
Example:
$dbh = new PDO($dsn);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$keyvals = [
'id' => isset($_POST['id']) ? h( $_POST['id'] ) : null,
'title' => isset($_POST['title']) ? h( $_POST['title'] ) : null,
'description' => isset($_POST['description']) ? h( $_POST['description'] ) : null,
'created_at' => time(),
'created_by' => 1,
];
$last_ids[] = pdo_insert($dbh,'products',$keyvals);
Upvotes: -1
Reputation: 47321
function pdo_insert($table, $arr=array())
{
if (!is_array($arr) || !count($arr)) return false;
// your pdo connection
$dbh = '...';
$bind = ':'.implode(',:', array_keys($arr));
$sql = 'insert into '.$table.'('.implode(',', array_keys($arr)).') '.
'values ('.$bind.')';
$stmt = $dbh->prepare($sql);
$stmt->execute(array_combine(explode(',',$bind), array_values($arr)));
if ($stmt->rowCount() > 0)
{
return true;
}
return false;
}
pdo_insert($table, array('title'=>$title, 'userid'=>$user_id, 'post'=>$body));
Upvotes: 18