从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。

我在这里读到:

如果使用,则无法从同一行返回另一列PDOStatement::fetchColumn()获取数据

在java中,有一个ResultSet#getString()函数来做这个。

与此等价的PHP代码是什么?

您可以使用:

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

请读

fetchColumn(),从结果的下一行返回单个列集。

使用PDO::fetchAll():

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

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