2016-06-18 68 views
-2

我正在尝试用PHP创建一个登录/注册码,它将注册数据发送到数据库。我调用execute()方法,但出于某种原因,它不起作用。应该发生什么是该方法发送SQL语句到数据库我忽略了什么?PHP PDO :: execute语句不会执行

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; 
} 

我验证有连接到数据库没有问题了,里面查询其他方法(i)根据需要

+1

请编辑你的问题来澄清它。寻求调试帮助的问题(“**为什么不是这个代码工作?”)必须包括所需的行为,*特定的问题或错误*和*在问题本身中重现它*所需的最短代码* *。没有**明确问题陈述**的问题对其他读者没有用处。请参阅:[如何创建一个最小,完整和可验证的示例。](http://stackoverflow.com/help/mcve) –

+0

您可以详细说明'它不起作用'吗? –

+0

为什么创建一个名为query的函数时,该函数自己已经存在? –

回答

0

使用PDO::errorInfo()检索错误消息被调用的函数或设置PDO optionPDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION如此发生错误时,PDO会引发异常。

+0

好吧,我跑了,但我是新来的语言,并不真正明白这是什么意思 - > PDO :: errorInfo():Array([0] => 21S01 [1] => 1136 [ 2] =>列计数与第1行的值计数不匹配 – tornadoriley

+0

这意味着您有太多或没有足够的绑定值来覆盖您在sql语句中使用的数量。 – Rasclatt

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; 
} 
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(); 

,如果这是越来越成功,然后尝试结合数据。 我总是有办法摆脱错误。