doukuiqian5345 2012-11-20 09:16
浏览 30
已采纳

使用PDO在mysql中插入数据[关闭]

Hi guys I have Table "Item" that have a "Name" field. I am trying to insert a data but I am getting an error. Please see my below code for further information.

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

Error:

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

2条回答 默认 最新

  • dpa55065 2012-11-20 09:24
    关注

    Your $pair array looks like this:

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

    Which is nonsense. The execute() method expects an array with named keys, not numeric keys with garbage values. Get rid of the $pair thing entirely and pass $attributes to execute() instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成