2015-12-05 111 views
-1

我在嘗試將我的網站轉換爲PDO,並且我的登錄頁面出現了一些問題。 這是我的代碼,但無論輸入什麼用戶名或密碼,我都得到了同樣的結果:「姓名或密碼不正確!」。我檢查了用戶名和密碼,它是正確的。 有什麼問題?在PDO中登錄頁面

<?php 
    if($_POST['name']=="" || $_POST['password']=="")`enter code here` 
    { 
     print 'Fields cannot be empty !<br> 
       <a href="index.php">Inapoi</a>'; 
     exit; 
    } 

    include("connnect.php"); 
    $stmt = $db->prepare('SELECT * FROM admin WHERE admin_name = ? AND admin_password = ?'); 
    $stmt->bindParam(1, $_POST['name']); 
    $stmt->bindParam(2, md5($_POST['password'])); 
    $stmt->execute(); 

    if(($stmt->fetchColumn())!=1) 
    { 
     print 'Name or password is incorrect!<br> 
       <a href="index.php">Back</a>'; 
     exit; 
    } 

    session_start(); 
    $_SESSION['name_admin']=$_POST['name']; 
    $_SESSION['password']=md5($_POST['name']); 
    $_SESSION['key_admin']=session_id(); 
    header("location: admin.php"); 
?> 
+1

'var_dump(($ stmt-> fetchColumn()); ' –

+0

fetchColumn將永遠不會是1,它將返回列值或FALSE.Just刪除'!= 1' – Mihai

+0

@Mihai如果列值爲1 - 那麼是什麼? –

回答

2

fetchColumn

PDOStatement::fetchColumn — Returns a single column from the next row of a result set

而不是$stmt->fetchColumn()你必須使用$stmt->rowCount()

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

if($stmt->rowCount()>0) 
    { 
     print 'Name or password is incorrect!<br> 
       <a href="index.php">Back</a>'; 
     exit; 
    } 

http://php.net/manual/en/pdostatement.rowcount.php

更新

PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned

$stmt = $db->prepare("SELECT * FROM admin WHERE admin_name = ? AND admin_password = ?"); 
     $stmt->bindParam(1, $_POST['name']); 
     $stmt->bindParam(2, md5($_POST['password'])); 
     $stmt->execute(); 
     $result=$stmt->fetch(); 
     $row=count($result); 
      /* Check the number of rows that match the SELECT statement */ 
      if ($row== 0) { 
       print 'Name or password is incorrect!<br> 
        <a href="index.php">Back</a>'; 
      exit; 
      } 
+1

對於SELECT這不會工作,你需要一個SELECT COUNT或存儲所有值與fetchAll – Mihai

+0

@Mihai之前你是正確的,我會相應地更新我的答案。並感謝更新我的知識 – Saty

+0

現在我得到這個致命錯誤:調用未定義的方法PDOStatement ::查詢().. – greeny

0

1)include("connnect.php");之前添加var_dump($_POST['name']); var_dump($_POST['password']); exit;

2)然後,如果你的名字和密碼$stmt->execute();後加入添加var_dump($stmt); exit;

3)如果什麼都沒有輸出,所以問題出在你的PDO配置

+0

我有我的密碼和用戶名.. – greeny

+0

ok,現在你可以刪除'var_dump($ _ POST ['name']);的var_dump($ _ POST [ '密碼']);退出;'做第二個(2分) –

+0

現在我得到了這個:object(PDOStatement)#3(1){[「queryString」] => string(61)「SELECT * FROM admin WHERE admin_name =?AND admin_password =? 「 } – greeny