在php中从结果集中获取特定列值
我的代码是:在php中从结果集中获取特定列值,php,prepared-statement,Php,Prepared Statement,我的代码是: 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
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()
function可以实现这一点
什么是PHP等价物?您可以使用:
$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type
请阅读
fetchColumn(),从结果的下一行返回单个列
设定
有关详细信息,请阅读。使用PDO::fetchAll()
:
或者只打印($rows)您会注意到它是一个关联数组。请使用格式化功能提高可读性。这次我是为你做的。另外,请解释为什么您的解决方案有效或有帮助。有关更多信息,请阅读中的文章。
$rows = $stmt->fetchAll();
foreach ($rows as $v) {
echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
}
}