php - PHP PDO返回单行

这是最优化的?


$DBH = new PDO("connection string goes here" );



$STH = $DBH -> prepare("select figure from table1" );



$STH -> execute();



$result = $STH -> fetch();



echo $result ["figure"];



$DBH = null;



问题:

如果我知道只能从数据库中得到1行,我不明白为什么还需要foreach循环,但是我不知道如何更改代码。


$DBH = new PDO("connection string goes here" );



$STH = $DBH -> prepare("select figure from table1" );



$STH -> execute();



$result = $STH -> fetchAll();



foreach( $result as $row ) {


 echo $row["figure"];


}



$DBH = null;



时间:

只有一行用fetch,所以不需要foreach循环


$row = $STH -> fetch();



例子(ty northkildonan ):


$dbh = new PDO(" --- connection string ---"); 


$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 


$stmt->execute(); 


$row = $stmt->fetch();




$DBH = new PDO("connection string goes here" );


$STH - $DBH -> prepare("select figure from table1 ORDER BY x LIMIT 1" );



$STH -> execute();


$result = $STH -> fetch();


echo $result ["figure"];



$DBH = null;



你可以通过设置提取类型来进行更多优化,请参见http://www.php.net/manual/de/pdostatement.fetch.php ,如果只通过列名访问它,则需要编号。

请注意ORDER ,使用ORDER或where获得所需的行,否则你就会得到表的第一行。

尝试:


$DBH = new PDO("connection string goes here" );


$row = $DBH->query("select figure from table1" )->fetch();


echo $row["figure"];


$DBH = null;



如果只需要一个字段可以使用fetchColumn而不是fetch http://www.php.net/manual/en/pdostatement.fetchcolumn.php


$param = $_GET[\'username\'];



$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");


$query->bindParam(\':param\', $param);


$query->execute();



$result = $query -> fetch();



print_r($result);



如何使用limit 0,1优化mysql优化

关于你的代码:


$DBH = new PDO("connection string goes here" );



$STH - $DBH -> prepare("select figure from table1" );



$STH -> execute();



$result = $STH ->fetch(PDO::FETCH_ASSOC)



echo $result["figure"];



$DBH = null;




$DBH = new PDO("connection string goes here" );


$STH - $DBH -> query("select figure from table1" );


$result = $STH -> fetchColumn();


echo $result;


$DBH = null;



...