Search code examples
phppdoresultsetassociative

How to get column names and values from a single-row resultset with PDO?


I need to get all column names and values in the row where id = $id.

Column names should be echoed as title; values should be echoed as story

Something like this:

function story($id) {
    global $db;
    $sql = "select *  from users where id = :aid limit 1";
    $st = $db->prepare($sql);
    $st -> execute([":aid" => $id]);
    $row = $st->fetch();
    $sql = // select all column names;
    $columns = // array - result of $sql
    $story = "";
    foreach ($columns as $el) {
        $i = array_search($el, $columns);
        $val = $row[$i];
        $story .=
        "<div class='title'>" . $el . "</div>\n" .
        "<div class='story'>" . $val . "</div>\n";
    }
    echo $story;
}

Solution

  • No need to do array_search(), do like below:-

    function story($id) {
        global $db;
        $sql = "select *  from users where id = :aid limit 1";
        $st = $db->prepare($sql);
        $st -> execute([":aid" => $id]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        if(count($row)>=1){
          foreach ($row as $column => $value) {
            echo "<div class='title'>" . $column . "</div>\n" .
            echo "<div class='story'>" . $value. "</div>\n";
          }
        }
    }