我有这个登录页面,我在看Udemy的教程时写了它.他的代码工作正常,但在我的代码(相同)中,我有以下错误:
致命错误:在非对象上调用成员函数prepare()
这是代码:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Adding a character set: $conn = exec("SET CHARACTER SET utf8mb4"); $user = ''; $pass = ''; $sum = 0; $error_msg = "Please type a username and a password"; if(isset($_POST['login_submit'])) { //Start a session: session_start(); $user = $_POST['username']; $pass = $_POST['password']; if(empty($user) && empty($pass)) { echo $error_msg; $pass = ''; } if(empty($user) || empty($pass)) { echo $error_msg; $user = ''; $pass = ''; } if(!empty($user) && !empty($pass)) { //SQL: $query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1"); $query->bindParam(":u", $user); $query->bindParam(":p", $pass); //Execute query: $query->execute(); $number_rows = $query->fetch(PDO::FETCH_NUM); if($number_rows>0) { echo $user; $_SESSION = $user; $_SESSION = $pass; header("Location: /pages/home.php"); } else { echo "Invalid username or password"; header("Location: index.php"); } //echo $user; } } if(!isset($_POST['login_submit'])) { echo "Login button not clicked"; } ?>
trincot.. 6
使用以下语句销毁$ conn对象:
$conn = exec("SET CHARACTER SET utf8mb4");
替换为:
$conn->exec("SET CHARACTER SET utf8mb4");
请注意,从PHP 5.3.6开始,您可以在连接字符串中设置字符集,如下所示:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);
exec
然后不再需要单独的呼叫.
使用以下语句销毁$ conn对象:
$conn = exec("SET CHARACTER SET utf8mb4");
替换为:
$conn->exec("SET CHARACTER SET utf8mb4");
请注意,从PHP 5.3.6开始,您可以在连接字符串中设置字符集,如下所示:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);
exec
然后不再需要单独的呼叫.