PDO获取(PDO :: FETCH_ASSOC)不返回值

First of all, this has something to do with Login.

I'm trying to store the values from the database into my $_SESSSION variables. At first, I tried to select all rows where username = user and password = password and so on.

If it returns > 0, then I tried to fetch(PDO::FETCH_ASSOC) to get the rows of it. The problem is, although it returns > 0 , it FETCH_ASSOC doesn't to return the values to me.

Here's what I tried so far.

<?php
if(isset($_POST['btn_Save'])){
  $uname  = $_POST['username'];
  $pword  = $_POST['password'];
  $q = "SELECT * FROM `users` WHERE `username` = :username AND `password` = :password";
  $sql = $db->prepare($q);
  $sql->bindParam(":username",$uname);
  $sql->bindParam(":password",$pword);
  $sql->execute();
  $rows = $sql->fetch(PDO::FETCH_NUM);
  if($rows > 0){
  $rows2 = $sql->fetch(PDO::FETCH_ASSOC);
  echo $rows2['userID'];
    $_SESSION['account'] = $rows2['userID'];
    $_SESSION['name']    = $rows2['firstName'];
 //echo" <meta http-equiv='refresh' content='0;url=index.php'>";
  }
  else{
    echo"<script>alert('No user found!');</script>";
   // echo" <meta http-equiv='refresh' content='0;url=index.php'>";

  }

PDO::FETCH_NUM:

returns an array indexed by column number as returned in your result set, starting at column 0

So can't compare your array with your if condition below

$rows = $sql->fetch(PDO::FETCH_NUM);
if($rows > 0){

In your code your are trying to fetch data two times. You can do it in single time

Use it as

$q = "SELECT * FROM `users` WHERE `username` = :username AND `password` = :password";
$sql = $db->prepare($q);
$sql->bindParam(":username", $uname);
$sql->bindParam(":password", $pword);
$sql->execute();

$rows2 = $sql->fetch(PDO::FETCH_ASSOC);
if (count($rows2) > 0) {
    $_SESSION['account'] = $rows2['userID'];
    $_SESSION['name'] = $rows2['firstName'];
    //echo" <meta http-equiv='refresh' content='0;url=index.php'>";
} else {
    echo"<script>alert('No user found!');</script>";
    // echo" <meta http-equiv='refresh' content='0;url=index.php'>";
}

Read about rowCount

Plus you are storing plain password into your database

Read Password hashing technique

http://php.net/manual/en/function.password-hash.php

http://php.net/manual/en/faq.passwords.php