draxq02664 2016-03-29 06:55
浏览 112
已采纳

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'>";

  }
  • 写回答

1条回答 默认 最新

  • doushi9444 2016-03-29 07:04
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 调用函数时,无关变量的改变引起函数值的改变
  • ¥15 xy坐标转化为经纬度坐标
  • ¥15 一般三角模糊数的上界值和下届值取中值的多少比较合理?
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥20 Hbase启动失败,无法启动HMaster
  • ¥15 sqpingboot在父模块已经引入了mybatisplus 在子组件不写版本号还是报错
  • ¥20 Lumerical FDTD solutions 中模型的相对阻抗,有效介电常数和有效磁导率的实部和虚部的数据如何获得?
  • ¥100 sql reporting service 远程smtp服务器配置支持
  • ¥15 ppyoloe_r带角度目标检测,loss_cls没法收敛
  • ¥15 淘宝交易指数如何解读,其关联的数据指标是什么