[英]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。
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等效于什么?
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.