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

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

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元