我无法弄清楚为什么这不起作用。我是新人,只是在学习。
的login.php
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?> <?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?> <?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?>
user.php的
<?php
require_once 'core/classes/Connect.php';
class User {
private $db;
public function __construct() {
$this->db = new Connect();
$this->db = $this->db->dbConnect();
}
public function userExists($username) {
$st = $this->db->prepare("SELECT COUNT(user_id) FROM users WHERE username=?");
$st->bindParam(1, $username);
$st->execute();
if ($st->rowCount() == 1) {
return true;
} else return false;
}
}
?>
我一直在学习OOP,每个人都告诉我学习的最好方法是尝试而不是寻求帮助。我想建立一个简单的登录,然后使它更复杂。
当我输入正确的用户名时,它不会echo
正常。相反,echo
我们无法找到该用户名。你注册了吗?请帮忙。感谢
答案 0 :(得分:2)
我不知道您的Connect
- 类(尤其是方法rowCount
)如何工作,但问题似乎如下:您的查询返回具有给定用户名的user_ids数但你算数行。
更换
$st = $this->db->prepare("SELECT COUNT(user_id) FROM users WHERE username=?");
与
$st = $this->db->prepare("SELECT user_id FROM users WHERE username=?");
应该这样做。
因为你正在学习更多评论:
empty($username) === true
等于empty($username)
。大多数程序员更喜欢后者(因为它更短)。
将方法userExists
声明为静态似乎更有意义。