2013-03-25 108 views
0

我不明白爲什麼這不起作用。我是新的,只是學習。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 ok。相反,它echo我們無法找到該用戶名。你有沒有註冊?請任何幫助。謝謝

回答

2

我不知道你的Connect類(尤其是方法rowCount)是如何工作的,但問題似乎如下:你的查詢返回給定用戶名的user_id數目,但你計數行。

更換

$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聲明爲靜態似乎更有意義。

+0

謝謝我只是在學習,但在這裏的幫助,我會再次學習更快,更好地再次感謝 – ivor 2013-03-26 00:06:18

+0

Re:比較'true'或'false',我會說後者是方法/函數的返回值是一個布爾值。將布爾值與另一個布爾值進行比較是多餘的。 – 2013-03-26 00:07:03