2014-08-30 2 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로이 경우 연결이 입니다 그렇게을 만들지 먼저 db_connection 통화 중 연결 오류가 발생했습니다 경우에만 두 번 db_connection를 호출합니다.

그러나 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); 
    } 
} 
관련 문제