fetch single record using PHP PDO and return result

后端 未结 2 1317
终归单人心
终归单人心 2021-01-29 12:05

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

            


        
相关标签:
2条回答
  • 2021-01-29 13:03

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

    • 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

    So, change the code to this

    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();
    

    or multiple rows

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

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

    0 讨论(0)
  • 2021-01-29 13:07

    You are not executing your Query?!

    $dbh = new PDO("connection string"); 
    $get_row = $dbh->prepare($sql); 
    $get_row->execute(); 
    $row = $get_row->fetch();
    

    Try this for get Single Row of all column.

    0 讨论(0)
提交回复
热议问题