gpt4 book ai didi

php - 我的 pdo 登录功能需要帮助

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:56 24 4
gpt4 key购买 nike

我正在使用 PDO 制作登录系统,但我的代码出现了一些问题。

我的问题是,当我按下提交按钮时,我收到一条错误消息:“ fatal error :找不到类‘User’”在我的 index.php 中。

有谁能帮我找到解决问题的方法吗?

索引.php:

<?php 
session_start();
include_once('connection.php');
if(isset($_POST['submit'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$object = new User();
$object->Login($user, $pass);
}
?>

<html lang="en">
<head>
</head>

<body>
<form method="post" action="index.php">
Username: <input type="text" name="user" />
Password: <input type="text" name="pass" />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>

用户.php:

<?php
include_once('connection.php');
class User{

private $db;

public function __construct(){
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function Login($user, $pass){
if(!empty($user) && !empty($pass)){
$st = $this->db->prepare("SELECT * from users WHERE username=? AND password=?");
$st->bindParam(1, $user);
$st->bindParam(2, $pass);
$st->execute();

if($st->rowCount() == 1){
echo "User verifies, Access granted";
} else {
echo "Incorrect Username or Password";
}
}else{
echo "Please enter Username and Password";
}
}
}
?>

连接.php:

<?php
class Connection{
public function dbConnect(){
return new PDO('mysql:host=localhost; dbname=test', 'root', 'password');
}
}
?>

最佳答案

好的,让我们分析一下错误信息。 fatal error :找不到类“用户”

Fatal error

好的,我们有一个 fatal error ,一个停止程序的错误。让我们看看,或者我们有一些额外的信息。

Class 'User' not found

嗯,php 好像找不到类User。好的,让我们看看我们的 index.php 文件。嗯,的确如此。 index.php 中没有定义 User 类

啊哈,这就是问题所在。那么,让我们告诉 php 在哪里可以找到 User 类:

include 'User.php';

好了,这样更好。

Those Error messages are really helpfull


编辑:

这段代码有味道

你不是在使用 class 这个词,而是在骚扰它。

  • 您的 User 类与您的 Connection 类紧密耦合。
  • 每次调用 dbConnect()
  • 都会创建一个新的 PDO 对象
  • 你的用户类实际上是一个登录函数
  • 代码约定是“404 not found”(查看 PSR-1 和 PSR-2)
  • 如果包含 user.php,您也会尝试包含数据库。您可以使用 include_once 解决这个问题。但这只是在说:“我不知道它是否已包含在内,所以让我简单地使用 include_once”(查看自动加载或使用 boot.php 脚本)

对不起,我的意思是恭喜你!

很抱歉,让我们面对现实吧。你正在使用 PDO!这真的很棒 :) 因此,请使用有效的工具继续做好工作。祝你好运!

关于php - 我的 pdo 登录功能需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23913516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com