从 php 中的结果集中获取特定列值

Fetch specific column value from result set in php

我的代码是:

try 
        {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);

            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $conn->prepare("select userid,fname,type from native_users where email=:email and pass=:pass");
            $stmt->bindParam(':email', $username);
            $stmt->bindParam(':pass', $password);
            $stmt->execute();

            if($stmt->rowCount() > 0)
            {
                $_SESSION['uid']=$stmt->fetchColumn(0); //working

                $_SESSION['fname']=$stmt->fetchColumn(1); //not working
                $utype=$stmt->fetchColumn(3); // not working

                if($utype == "admin")
                {
                    // send to admin page 
                }
                else
                {
                    //send to user page
                }
            }
            else
            {
                echo"Incorrect data.";
            }
        }
        catch(PDOException $e)
        {
            echo "Error: " . $e->getMessage();
        }
        $conn = null;

我是PHP的新手,我基本上Java。

我读 here 是:

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

在 java 中,有 ResultSet#getString() 函数可以做到这一点。

PHP 相当于什么?

您可以使用:

$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type

请阅读this

fetchColumn(), Returns a single column from the next row of a result set.

详情请阅读this

使用PDO::fetchAll()

$rows = $stmt->fetchAll();       
    foreach ($rows as $v) { 
      echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
    }        
  }

或者只是 print_r($rows) 你会注意到它是一个关联数组。