2017-02-13 96 views
1

我想通過類內的函數連接到MySql。同樣可以做得更容易,但這也是一種學習體驗。代碼全部按預期工作,但是如果MySql查詢失敗,mysqli_error()返回空白,並且mysqli_errno()返回0.我發現手動將數據輸入到mysql中時出錯,並且它是db中太短的列,但是我不明白爲什麼mysqli_error()和mysql_errno()沒有報告錯誤。預先感謝您的幫助。從php類報告mysql錯誤報告0

<?php 

class FrmAddProduct { 

    protected function getDbConnection(){ 
     return new mysqli("localhost", "root", "****", "test"); 
    } 

    /** 
    *all variables are declares and assigned here 
    * 
    **/ 
    function commitSignUp(){ 
     $commitSignUp = "INSERT INTO Login (`logTitle`,`logFirstName`, `logLastName`,`logLandLine`,) VALUE (\"$this->title\", \"$this->firstName\",\"$this->lastName\", \"$this->landLine\",)"; 
     if ($this->getDbConnection()->query($commitSignUp)){ 
      echo "The new product is added."; 
      return 1; 
     } else { 
      echo "Mysql reported this error description: ".mysqli_error($this->getDbConnection()."<br>"; 
       echo "Mysql reported this error number: ".mysqli_errno($this->getDbConnection()); 
       return 0; 
     } 
+0

你混合MySQLi的OOP風格和程序式...使用一個或另一個,你不能混用。閱讀手冊中的更多內容:http://php.net/manual/en/mysqli.error.php –

回答

1

無論你在這裏做什麼是完全錯誤的做法。您正在創建兩次或三次連接的實例。而且你期望在那裏寫出錯誤。

以這種方式更改您的代碼。

protected function getDbConnection(){ 
    return mysqli_connect("localhost", "root", "****", "test"); 
} 

而且這樣做太

function commitSignUp(){ 
     $commitSignUp = "INSERT INTO 
          Login (
            `logTitle`, 
            `logFirstName`, 
            `logLastName`, 
            `logLandLine`, 
            ) 
          VALUE (
             \"$this->title\", 
             \"$this->firstName\", 
             \"$this->lastName\", 
             \"$this->landLine\", 
         )"; 

      $conn = $this->getDbConnection(); 

      if ($conn->query($commitSignUp)) { 
       echo "The new product is added."; 
       return 1; 
      } else { 
       echo "Mysql reported this error description: ".mysqli_error($conn."<br>"; 
       echo "Mysql reported this error number: ".mysqli_errno($conn); 
       return 0; 
      } 
+0

這不會改變主要問題。它仍然會執行與OP當前代碼相同的事情。 –

+0

你有沒有嘗試過。 – Vinay

+0

多連接的唯一問題。 – Vinay