PHP MySQL结果-不必要地使用foreach
我使用此方法访问我的MySQL数据库:PHP MySQL结果-不必要地使用foreach,php,mysql,foreach,resultset,Php,Mysql,Foreach,Resultset,我使用此方法访问我的MySQL数据库: $STH = $DBH->prepare("SELECT email FROM user WHERE unum = :u"); $STH->bindParam(':u', $json['u']); // Example only try { $STH->execute(); $STH->setFetchMode(PDO::FETCH_ASSOC); } catch(PDOException $e) { ech
$STH = $DBH->prepare("SELECT email FROM user WHERE unum = :u");
$STH->bindParam(':u', $json['u']); // Example only
try {
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
现在,我知道$STH只包含一行,但我总是这样做:
foreach($STH as $row){
... $row['email']... etc
foreach的foreach
完全没有必要,并且使代码更难遵循。我如何在$STH
中访问电子邮件
,而不使用foreach
谢谢。只需使用
$row = $STH->fetch(PDO::FETCH_ASSOC);
echo $row['email'];
应该做你的把戏你可以用
$row = $STH->fetch();
echo $row['email'];
它将只获取1行。$row=$STH->fetch()代码>也可以作为
$STH->setFetchMode(PDO::FETCH_ASSOC)代码>已经被定义。甚至只是echo$STH->fetchColumn()
,甚至只是echo$STH->fetchColumn()代码>。