2016-06-18 82 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(); 

,如果這是越來越成功,然後嘗試結合數據。 我總是有辦法擺脫錯誤。