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

查看:24
本文介绍了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"部分,它非常适合从数据库中返回许多行.

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 返回单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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