PHP PDO fetch returns a array?

14,334

Solution 1

You didn't specify a fetch_style parameter. It returns FETCH_BOTH by default, which is an array. Here are the options and how to specify it: http://php.net/manual/en/pdostatement.fetch.php

EDIT: Also, it will always return an array, even if there's only one column, because a row can contain multiple attributes. You can use FETCH_ASSOC and then specify your column name to get the data, or, if you just use fetch() like you did, the array is indexed by both the column name and the 0-indexed column number.

Solution 2

If you want to get just the column, you need the fetchColumn() method of PDOStatement.

Solution 3

The resultset is fetched line by line, even if the line contains a single column

Share:
14,334
Adam Ramadhan
Author by

Adam Ramadhan

be foolish, stay hungry. ⚡ Web Crawling & NER Related ⚡ Hosting & Infrastructure ⚡ Broadband ISP & Its Software

Updated on June 07, 2022

Comments

  • Adam Ramadhan
    Adam Ramadhan almost 2 years
    $GetUid = $dbConnect->prepare("SELECT UID FROM users WHERE username = :username");
    $GetUid->execute($RegisterData3);
    $UserID = $GetUid->fetch();
    

    why does it return array not a string ?

    var_dump('$UserID') says

    array
      'UID' => string '45' (length=2)
      0 => string '45' (length=2)
    

    it should be

    array
      'UID' => string '45' (length=2)
    

    update* what about the 0 ? where does it came from ? thanks for the replies.