oop无法让这个小脚本正常登录

时间:2013-03-25 23:32:19

标签: php oop

我无法弄清楚为什么这不起作用。我是新人,只是在学习。

的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我们无法找到该用户名。你注册了吗?请帮忙。感谢

1 个答案:

答案 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声明为静态似乎更有意义。