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