PHP PDO :: execute语句将不会执行

时间:2016-06-18 13:47:11

标签: php mysql pdo execute

我正在尝试使用PHP创建登录/注册代码,该代码将注册数据发送到数据库。我调用了execute()方法,但由于某种原因它不起作用。应该发生的是该方法将SQL语句发送到数据库我可以忽略什么?

public function query($sql, $params= array()) {
    /* query takes 2 paramaters, $sql which is a prepared sql statement, and params, which holds the value of the fields to be inserted into db */
    $this->_error = false; // field to determine if there is an error
    $this->_query = $this->_pdo->prepare($sql); // $_query is another field holding the query value

        $x=1;
        if(count($params)){ //count is a function to determine if the paramater has a value
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }
        if($this->_query->execute($sql)){
            $this->_result = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount(); // this is the block that is desired to be executed
        } else {
            $this->_error = true; // This is the block that is being executed
        }
    return $this;
}

我验证连接到数据库没有问题,查询()中的其他方法被调用的功能是

3 个答案:

答案 0 :(得分:1)

pdo执行参数可能不是查询。执行时只允许绑定数组。尝试:

public function query($sql, $params= array()) {
    /* query takes 2 paramaters, $sql which is a prepared sql statement, and params, which holds the value of the fields to be inserted into db */
    $this->_error = false; // field to determine if there is an error
    $this->_query = $this->_pdo->prepare($sql); // $_query is another field holding the query value

        $x=1;
        if(count($params)){ //count is a function to determine if the paramater has a value
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }
        if($this->_query->execute()){ // changed execute($sql) to execute()
            $this->_result = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount(); // this is the block that is desired to be executed
        } else {
            $this->_error = true; // This is the block that is being executed
        }
    return $this;
}

答案 1 :(得分:0)

使用PDO::errorInfo()检索错误消息或将PDO option PDO::ATTR_ERRMODE设置为PDO::ERRMODE_EXCEPTION,以便PDO在出现错误时抛出异常。

答案 2 :(得分:0)

首先,您必须手动尝试查询, 喜欢

$db = new PDO("mysql:host=somehost;dbname=somedb","user","pass");
$stmt = $db->prepare("insert into table (a,b,c) values('1','2','3')");
$stmt ->execute();

如果这成功,那么您尝试绑定数据。 我总能找到摆脱错误的方法。