PHP PDO返回单行 [英] PHP PDO returning single row

查看:43
本文介绍了PHP PDO返回单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新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"部分,它是从数据库返回许多行的很好的IMO.

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):

$dbh = new PDO(" --- connection string --- "); 
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
$stmt->execute(); 
$row = $stmt->fetch();

这篇关于PHP PDO返回单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆