更新 2:
那么这是可以得到的最优化的吗?
So is this the most optimized it can get?
$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:
我知道我可以为 sql 查询添加限制,但我也想摆脱我不需要的 foreach 循环.
I know I can add limit to the sql query, but I also want to get rid of the foreach loop, which I should not need.
原始问题:
我有以下脚本,由于foreach"部分,它非常适合从数据库中返回许多行.
I have the following script which is good IMO for returning many rows from the database because of the "foreach" section.
如果我知道我总是只能从数据库中获取 1 行,我该如何优化它.如果我知道我只会从数据库中获取 1 行,我就不明白为什么需要 foreach 循环,但我不知道如何更改代码.
How do I optimize this, if I know I will always only get 1 row from the database. If I know I will only ever get 1 row from the database, I don't see why I need the foreach loop, but I don't know how to change the code.
$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;
随便取.只得到一排.所以不需要 foreach 循环 :D
Just fetch. only gets one row. So no foreach loop needed :D
$row = $STH -> fetch();
示例(ty northkildonan):
example (ty northkildonan):
$id = 4;
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
这篇关于PHP PDO 返回单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!