2016-08-29 51 views
1

在我的数据库类中,我有一个方法query(),它将SQL语句和参数作为参数并在数据库中运行它们。BindParam()无法正常工作

// the parameters are the sql statement and the values, returns the the current object 
    // the result set object can be accessed by using the results() method 

    public function query($sql, $params = array()) { 

     $this->_error = false; // initially the error is set to false 

     if($this->_query = $this->_pdo->prepare($sql)) { 

      // if the parameters are set, bind it with the statement 
      if(count($params)) { 
       foreach($params as $param => $value) { 
        $this->_query->bindParam($param, $value); 
       } 
      } 

      // if the query is successfully executed save the resultset object to the $_results property 
      // and store the total row count in $_count 
      if($this->_query->execute()) { 
       $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 
       $this->_count = $this->_query->rowCount(); 
      } else { 
       $this->_error = true; 
      } 
     } 

     return $this; 

    } 

,这是怎么了调用该方法

$db->query("SELECT * FROM users WHERE username = :username AND id = :id ", array(':username' => 'sayantan94', ':id' => 1)); 

但是,当我print_r()结果集,我得到一个空数组。但是,如果我这样做

$db->query("SELECT * FROM users WHERE username = :username", array(':username' => 'sayantan94')); 

或本

$db->query("SELECT * FROM users WHERE id = :id ", array(':id' => 1)); 

我得到正确的结果。我的代码有什么问题?

回答

2

除了什么是对方回答说,大部分代码是无用的或有害的。事实上,你只需要这几行

public function query($sql, $params = array()) 
{ 
    $query = $this->_pdo->prepare($sql); 
    $query->execute($params); 
    return $query; 
} 

它会尽你所能的功能,但没有那么多的代码和没有讨厌的副作用。想象一下你会在循环中运行一个嵌套的查询。第二次查询执行后,你的$ this - > _ results变量会变成什么?在这样的函数中,不应该有与特定查询相关的类变量。

此外,

  • 无需手动检查准备的结果 - PDO将被自己抛出异常
  • 没有必要为_error变量,因为它是好看不中用,而PDO自身的异常是方式更有用和信息性更强
  • 无需绑定循环 -​​可以一次绑定所有参数
  • 无需测试$params数组 -​​也将接受一个空数组。
  • 无需返回fetchAll() restult - 你总是可以做到这一点后,通过链接像这样$data = $db->query($sql, $params)->fetchAll();
  • 没有必要rowCount() - 你总是可以只统计数组从使用fetchall()
+0

This工作。谢谢你的建议。我现在在学习。 –

+0

@SayantanDas请查阅我的文章,以深入解释您正在使用的一些不良做法,[您的第一个数据库包装的儿童疾病](https://phpdelusions.net/pdo/common_mistakes) –

+0

谢谢。我一定会检查那篇文章。 –

1

您的foreach是假的,通过价值$价值,因为bindParam需要& $变量,做一个参考,试试这个:

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

http://php.net/manual/en/pdostatement.bindparam.php

+0

我回到获取此错误警告:PDOStatement :: bindParam():SQLSTATE [HY093]:无效的参数编号:列/参数是基于1的D:\ xampp \ htdocs \ oop \ classes \ DB.php在第50行上 –