2014-08-30 44 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); 
    } 
}