2014-08-30 75 views
1

粗体部分是我质疑的部分。在search_for_new_user函数内部,如果我将$conn->prepare更改为$this->db_connection()->prepare。我收到丢失的连接错误。但是,在上面的功能db_conn_test我可以使用这种语法。在这两种情况下,我都会返回$connection,所以我不明白为什么在语法上必须有所不同。准备好的语句数据库连接必须首先实例化吗?

class Database { 

    function db_connection() { 
     $server = "localhost"; 
     $user = "user"; 
     $password = "password"; 
     $database = "database"; 

     return $connection = new mysqli($server, $user, $password, $database); 
    } 

    function db_conn_test() { 
     if (**$this->db_connection()->connect_errno**) { 
      die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error); 
     } else { 
      echo "connected to mysql database"; 
     } 
    } 

    function search_for_new_user($email) { 
     **$conn = $this->db_connection();** 
     if ($stmt = **$conn->prepare**("SELECT email FROM users where email = ?")) { 
      $stmt->bind_param("s", $email); 
      $stmt->execute(); 
      $stmt->bind_result($result); 
      $stmt->fetch(); 
      echo $result; 
      $stmt->close(); 
      $conn->close(); 
     } 
    } 
} 

回答

0

db_conn_test你叫db_connection只有两次,如果第一次db_connection通话过程中得到了连接错误,所以在这种情况下,连接DB是不会创建

但是在search_for_new_user中,您创建连接两次。

即: 在db_conn_test

// if connection not created, because you got error 
if ($this->db_connection()->connect_errno) { 
    // therefore each time you call db_connection(), 
    // you again try create connection, and got same error 
    // and return it in die text 
    die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error); 
} else { 
    echo "connected to mysql database"; 
} 

search_for_new_user:你叫db_connection(),并创建连接(如果一切正常)。然后,如果您在第二次尝试中拨打db_connection,则第一个连接将消失,并且出现错误。

你的类应该是这样的:

class Database { 
    protected $connection; 

    function db_connection() { 
     if ($this->connection !== null) { 
      return $this->connection; 
     } 

     $server = "localhost"; 
     $user = "user"; 
     $password = "password"; 
     $database = "database"; 

     return $this->connection = new mysqli($server, $user, $password, $database); 
    } 
}