使用OOP时数据库未连接

时间:2019-05-10 22:38:59

标签: php oop

开始学习OOP编程,并想为我的数据库做一个蓝图。

一切正常,直到插入为止,然后无效。没有错误,但它确实输出了echo "This did not work"。感谢您的任何事先帮助!

我知道这并不安全,我只是在本地尝试自己的技能以学习:)

<?php    

class ConnectToDatabase {

    private $servername = "localhost";
    private $username = "root";
    private $password = "";
    private $dbname = "login";
    public $conn;

    function connect() {
        $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);

        if ($this->conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        echo "<br>Connect successfully!";
    }

    function insert($username, $password) {
        $sql = "INSERT INTO `logindetails`(`username`, `password`) VALUES ($username, $password)";

        if ($this->conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "This did not work..";
        }
    }
}

$db = new ConnectToDatabase;
$db->connect();
$db->insert("hello", "didThisWork?");

0 个答案:

没有答案