MySQLi和OOP PHP错误

时间:2014-01-02 07:14:46

标签: php oop mysqli

Parse error: syntax error, unexpected '$this' (T_VARIABLE), expecting function (T_FUNCTION) in C:\xampp\htdocs\Login-OOP\classes\class.user.php on line 28

以上是我得到的错误,我的class.user.php是:

<?php
class Users {
    public $db;
    public function __construct() {
        $this->db = new mysqli("localhost", "root", "<removed for privacy>", "oop");
    }

    public function login($username, $password) {
        $stmt = $this->db->prepare("SELECT username, password FROM users WHERE username=$username AND password=$password");
        $stmt->bind_param('ss', $username, $password);
        $stmt->execute();
        $stmt->bind_result($username, $password);
        $stmt->store_result();
        if($stmt->num_rows == 1) {
            while($stmt->fetch()) {
                $_SESSION['username'] == $username;
                header("Location: home.php");
                exit;
            }
        }
        else {
            header("Location: index.php?e=invalidlogin");
            exit;
        }
        $stmt->close();
        $stmt->free_result();
    }
    $this->db->close();
}
?>

那么,有什么可以做的吗?我试图访问我的index.php所以,如果你需要我的index.php,这里是:

<?php
    session_start();

    include "classes/class.user.php";

    if(isset($_REQUEST['submit'])) {
        extract($_REQUEST);
        $login = $users->login($username, $password);
    }
?>
<!DOCTYPE html>
<head>
    <title>Login</title>
</head>
<body>
    <form method="POST" action="" name="submit">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>

我希望这个错误有一个解决方案,我认为这是一个奇怪的错误。你能说出造成这个错误的原因吗?此外,如果我以安全的方式使用我的任何代码,请告诉我改善我的习惯。

2 个答案:

答案 0 :(得分:2)

将此$this->db->close();移到public function login($username, $password)

这是......

$stmt->free_result();
           }
           $this->db->close();
           }
         ?>

           $stmt->free_result();
           $this->db->close();
    }
}
?>

答案 1 :(得分:2)

你在这里弄错了。 $this->db->close();

尝试在destructor

中关闭数据库连接
public function __destruct() 
{
    $this->db->close();
}