准备好的语句数据库连接必须先实例化吗?

时间:2014-08-30 19:20:08

标签: php prepared-statement

粗体部分是我质疑的内容。在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();
        }
    }
}

1 个答案:

答案 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}}