使用PDO在mysql中插入数据

时间:2012-11-20 09:16:24

标签: php pdo

大家好我有表“项目”,其中包含“名称”字段。 我试图插入数据,但我收到一个错误。有关详细信息,请参阅我的以下代码。

item.php

class Item {

public function create(){
  $attributes = $this->attributes();
  $pair = array();

  foreach($attributes as $key => $value){
    $pair[] = "'{$key}'=>{$value}";
  }

  $bind = ":" . implode(", :",array_keys($attributes));
  $sql = "INSERT INTO " . static::$table_name
       . " (" . join(",",array_keys($attributes)) . " ) VALUES "
       . " ( " . $bind . " )";

  $stmt = $this->database->prepare($sql);
  $result = $stmt->execute($pair);
  if($result){
    return $result;
  } else {
    $error = $this->database->errorInfo();
  return $error;
  }
}

}

的index.php

<?php
   $item->name = "Sample Name";
   $item->create();
?>

错误:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in PATH on line 62

2 个答案:

答案 0 :(得分:1)

您的$pair数组如下所示:

array(
    0 => "'foo'=>bar"
    1 => ...
)

这是胡说八道。 execute()方法需要一个带有命名键的数组,而不是带有垃圾值的数字键。完全摆脱$pair事物并将$attributes传递给execute()

答案 1 :(得分:1)

$pair部分内容有误......您应该查看PDOStatement::executeArrays手册。

您的$pair数组如下所示:

array(1) {
  [0]=>
  string(12) "'key'=>value"
}

但它应该是:

array(1) {
  [":key"]=>
  string(5) "value"
}

自己找到解决方案:)