【发布时间】:2018-11-08 14:00:38
【问题描述】:
当我想在绑定值 php 风暴中使用 $this->stmt->bindValue() 时会出错:
在 PDO 中找不到方法绑定值
当我运行代码时,我看到了这个错误:
"PDOStatement::execute(): SQLSTATE[HY093]: 参数号无效:参数未在 C:\xampp\htdocs\oop\app\Model\DB.php 第 54 行定义
<?php namespace App\Model;
class DB
{
/**
* @var PDO <--- need by PhpStorm to find Methods of PDO
*/
protected $table ;
/**
* @var PDO <--- need by PhpStorm to find Methods of PDO
*/
protected $stmt ;
protected $bind=[] ;
protected $fetchMode = \PDO::FETCH_OBJ ;
public function __construct()
{
$config= require_once (__DIR__.'/../config.php') ;
try{
$this->pdo = new \PDO("mysql:host=127.0.0.1;dbname={$config['db']['database']}",$config['db']['username']
,$config['db']['password']) ;
} catch (\Exception $e)
{
die($e->getMessage());
}
} // end of constructor
public function select()
{
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table}") ;
$stmt->execute();
return $stmt->fetchAll() ;
} // end of select method
public function create($data)
{
$field = join(',',array_keys($data)) ;
$param = ':'. join(', :' , array_keys($data)) ;
$this->stmt = $this->pdo->prepare("INSERT INTO $this->table ($field) VALUES ($param)") ;
$this->bind = $data ;
$this->bindValue() ;
return $this->stmt->execute();
}
public function bindValue()
{
var_dump($this->stmt);
foreach ($this->bind as $key => $value){
$this->stmt->bindValue(":$key " , $value) ; //error
}
}
} // end of DB class
【问题讨论】:
-
了解如何调试。
-
您应该仔细阅读 PHP 文档中的参数化查询。您当前正在做的是构造一个不带参数的查询,然后将值绑定到那些不存在的参数。因此出现错误消息。
-
不确定
":$key "中的空间是否很大。