【问题标题】:php cant recognize pdo objects in other methodsphp无法识别其他方法中的pdo对象
【发布时间】: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 " 中的空间是否很大。

标签: php pdo binding


【解决方案1】:

在 PDO 中找不到方法绑定值

这是正确的。 PDO 类表示与数据库的连接,而不是单个查询/语句。为此,有 PDOStatement 类。

【讨论】:

  • 我该怎么办?此代码在我的朋友项目中有效。与他使用的代码完全相同
  • 从语法上讲,您的代码是正确的。为什么它对你不起作用,我们从这个 sn-p 看不到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
  • 2015-05-04
相关资源
最近更新 更多