2017-02-13 95 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