运行此代码时出现意外$ dbConn错误, 但我确实编写了$ dbConn的代码,我不知道为什么......
这里是我的user.php,包含登录数据库和用户表。
<?php
define('DB_NAME','login');
define('DB_SERVER','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
class User{
$dbConn = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME,DB_USERNAME,DB_PASSWORD);
$dbConn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
public function Login($name, $password){
if(!empty($name) && !empty($password)){
$statement = $dbConn->prepare("select * from users where name=? and password=?");
$statement->bindParam(1, $name);
$statement->bindParam(2, $password);
$statement->execute();
if($statement->rowCount() == 1){
echo "User verified, Access granted.";
}else{
echo "Incorrect username or password";
}
}else{
echo "Please enter username and password";
}
}
}
?>
以下是index.php
<?php
include_once('user.php');
if(isset($_POST['submit'])){
$name = $_POST['user'];
$password = $_POST['password'];
$object = new User();
$object->Login($name, $password);
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="index.php">
Username: <input type="text" name="user">
Password: <input type="text" name="password">
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
任何人都可以帮我解决我的问题吗? 非常感谢和赞赏。
答案 0 :(得分:1)
您不能在类之类的方法之外拥有可执行代码:
class User
{
$dbConn = new PDO(...);
$dbConn->setAttribute(...);
public function Login($name, $password){
}
}
如果要初始化某些内容,可以使用构造函数:
class User
{
protected $dbConn;
public function __construct()
{
$this->dbConn = new PDO(...);
$this->dbConn->setAttribute(...);
}
}