Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array of rows to PDO to insert them?

Tags:

php

mysql

pdo

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?

like image 493
CodeOverload Avatar asked Jan 03 '11 20:01

CodeOverload


1 Answers

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));
like image 61
ajreal Avatar answered Oct 30 '22 17:10

ajreal