使用PDO将数组数据插入mysql

时间:2013-11-06 14:54:09

标签: php arrays pdo

我有这个数组来自html表单的数据,我希望将这个数组插入到PHP函数中,该函数处理{mys}的INSERT查询。

如何将我的数组声明为PDO

   if (isset($_POST['submit'])); {
    $_POST['name'];
    $_POST['age'];


$myarray= array();
foreach ($_POST as $key => $value){
   $myarray[$key] = $value;
}

whatever($myarray);

}

functions whatever($myarray) {
    $sql=$db->prepare("INSERT INTO `user`(`name`, `age`) VALUES (:name,:age)");

    foreach($myarray as $row=>$value){
     $sql->bindValue(array($myarray)){
    }
    $sql->execute();
}
忘记错误的道歉。

这就是我得到的

    Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in C:\Web\xampp\htdocs\submit.php on line 36

    Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in C:\Web\xampp\htdocs\submit.php on line 36

    Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in C:\Web\xampp\htdocs\submit.php on line 36

    Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in 
C:\Web\xampp\htdocs\submit.php:38 Stack trace: #0 
C:\Web\xampp\htdocs\submit.php(38): PDOStatement->execute() #1 
C:\Web\xampp\htdocs\submit.php(12): register(Array) #2 {main} thrown in 
C:\Web\xampp\htdocs\submit.php on line 38

1 个答案:

答案 0 :(得分:1)

function pdoSet($fields, &$values, $source = array()) {
  $set = '';
  $values = array();
  if (!$source) $source = &$_POST;
  foreach ($fields as $field) {
    if (isset($source[$field])) {
      $set.="`".str_replace("`","``",$field)."`". "=:$field, ";
      $values[$field] = $source[$field];
    }
  }
  return substr($set, 0, -2); 
}

此函数将为SET运算符生成正确的序列

`field1`=:field1,`field2`=:field2

插入查询并存储$values数组中execute()数组的avtual数据值。

$fields = array('id','name','age','loc'); // allowed fields
$sql = "INSERT INTO `user` SET".pdoSet($fields,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);