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();
}
}
}