fetch single record using PHP PDO and return result

后端 未结 2 1318
终归单人心
终归单人心 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.

提交回复
热议问题