简体   繁体   English

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

[英]Fetch specific column value from result set in php

MY code is: 我的代码是:

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;

I am new to PHP, I basically do Java. 我是PHP新手,基本上是Java。

I read here that: 在这里读到:

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data. 如果使用PDOStatement :: fetchColumn()检索数据,则无法从同一行返回另一列。

In java, there is ResultSet#getString() funtion to do this. 在Java中,有ResultSet#getString()函数可以执行此操作。

What is the PHP equivalent of this? PHP等效于什么?

You can use: 您可以使用:

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

Please read this 请阅读

fetchColumn(), Returns a single column from the next row of a result set. fetchColumn(),从结果集的下一行返回单个列。

Please read this for detail. 请阅读详细。

Use PDO::fetchAll() : 使用PDO::fetchAll()

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

or just print_r($rows) you will notice that it's an associative array. 或只是print_r($rows)您会注意到它是一个关联数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM