如何将行数组传递给PDO以插入它们?

时间:2011-01-03 20:18:17

标签: php mysql pdo

我想使用PDO预处理语句,但我发现输入它真的非常耗时。如果有一个函数只传递以下关联数组,那将是非常有用的:

array(
"title"=>$title
"userid"=>$userid
"post"=>$body
)

请记住,数组中的键始终与SQL表中的行匹配。回顾一切,这应该切断键入:foo并在执行函数中再次输入它们的努力。

我特别谈到INSERT查询。

怎么做?

2 个答案:

答案 0 :(得分:18)

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

答案 1 :(得分:-1)

严格改进的PDO Insert功能,它还通过防止SQL注入攻击来考虑安全性:

// 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')));
}

示例:

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