使用 PHP PDO 获取单个记录并返回结果 [英] fetch single record using PHP PDO and return result

查看:57
本文介绍了使用 PHP PDO 获取单个记录并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在自定义php函数中获取包含所有列的单行并返回结果

how to fetch single row with all columns in custom php function and return result

这是我的自定义函数代码

here is my custom function code

function getdata($sql,$dbh)
 {

    $result=$dbh->prepare($sql);
    $res=$result->fetchAll(PDO::FETCH_ASSOC);
   // var_dump($res);
    return $res; 
 }

不工作......?

推荐答案

让我建议您稍微改变一下这种方法,使其更加灵活.

Let me suggest you to change this approach a bit, to make it A LOT more flexible.

  • 首先,您绝对必须让这个函数接受一个包含数据的数组用于 execute().否则,使用 prepare 或 PDO 将毫无意义.
  • 然后,让您的函数返回语句.这将使它非常灵活
  • First, you definitely have to make this function accept an array with data for execute(). Otherwise there will be no sense in using prepare or PDO at all.
  • Then, make your function return the statement. It will make it enormously flexible

所以,把代码改成这样

function getdata($dbh, $sql, $params = NULL)
{
    $stmt = $dbh->prepare($sql);
    $stmt->execute($params)
    return $stmt; 
}

这样你就可以获取任何一条记录.

this way you'll be able to fetch either single record.

$row = getdata($dbh, $sql)->fetch();

或多行

$row = getdata($dbh, $sql)->fetchAll();

甚至运行根本无法获取的插入或更新查询.

or even run insert or update queries from which you cannot fetch at all.

这篇关于使用 PHP PDO 获取单个记录并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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