PDOStatement :: execute():SQLSTATE [HY093]:

时间:2014-11-18 20:25:08

标签: php sql class

我想使用这个类查询:

class DB {
private static $_instance = null;   
private $_pdo,
        $_query,
        $_error = false,
        $_results,
        $_count = 0;

private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));          
    } catch(PDOException $e) {
        die($e->getMessage());
    }
}

public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }
    return self::$_instance;
}

public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach ($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        }else {
            $this->_error = true;
        }           
    } 
    return $this;
}

我正试图达到这样的查询方法:

$sql = "SELECT * FROM name 
                    WHERE namel LIKE :seek";
            $db = DB::getInstance();
            $db->query($sql, array(':seek' => $seek));

我收到这个警告: 警告:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:参数未在第36行的C:\ xampp \ htdocs \ blabla \ classes \ DB.php中定义

我甚至不确定我的方式达到DB类。

1 个答案:

答案 0 :(得分:1)

更新你的查询fn() - 问题在你的bindValue中你需要传递param和值来绑定

 public function query($sql, $params = array()) {
     $this->_error = false;
     if($this->_query = $this->_pdo->prepare($sql)) {

         if(count($params)) {
             foreach ($params as $param => $value) {
                 $this->_query->bindValue($param, $value);                               
             }
         }

         if($this->_query->execute()) {
             $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
             $this->_count = $this->_query->rowCount();
         }else {
             $this->_error = true;
         }           
     } 
     return $this;
 }

这取决于您的喜欢结果,如果您希望它显示开始,之后您必须像这样更新您的值:

$this->_query->bindValue($param, '%' . $value . '%'); 

我不知道你为什么要回来这个。

此外,如果您试图从课外获取结果,则需要公开才能访问该结果。

public $_results;