粗体部分是我质疑的内容。在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 :(得分:0)
db_conn_test
只有在第一次db_connection
通话期间出现连接错误时,才会db_connection
拨打search_for_new_user
两次,因此在这种情况下,与DB的连接未创建。
但是在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);
}
}
,第一次连接就会消失,你就会出错。
你的课应该是这样的:
{{1}}