問題描述
更新 2:
那么這是可以得到的最優(yōu)化的嗎?
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 循環(huán).
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 行,我該如何優(yōu)化它.如果我知道我只會從數據庫中獲取 1 行,我就不明白為什么需要 foreach 循環(huán),但我不知道如何更改代碼.
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 循環(huán) :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模板網!