如何将行数组传递给PDO以插入它们? [英] How to pass an array of rows to PDO to insert them?

查看:58
本文介绍了如何将行数组传递给PDO以插入它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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
)

请记住,数组中的键始终与SQL表中的行匹配.重述所有内容,这应该减少键入:foo并在execute函数中再次键入它们的工作.

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.

我特别在谈论INSERT查询.

I'm specifically talking about the INSERT query.

该怎么做?

推荐答案

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));

这篇关于如何将行数组传递给PDO以插入它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆