Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO fetch returns a array?

$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.

like image 889
Adam Ramadhan Avatar asked Jul 16 '10 12:07

Adam Ramadhan


People also ask

When using PHP PDOStatement fetch method the next row from a result set is retrieved?

Introduction to the PHP fetch() method Therefore, the subsequent call to the fetch() method will return the next row from the result set. To fetch all rows from a result set one by one, you typically use the fetch() method in a while loop. The fetch() method accepts three optional parameters.

What style of the fetch method can be used to return a row as an array indexed by column number?

By default, PDO returns each row as an array indexed by the column name and 0-indexed column position in the row. To request a different return style, specify one of the following constants as the first parameter when you call the PDOStatement::fetch method: PDO::FETCH_ASSOC.

Which function returns an array containing all the remaining rows in the resultset?

Return ValuesPDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set.

What does PDO fetchAll return?

Return Values ¶ PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.


1 Answers

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.

like image 67
rownage Avatar answered Oct 12 '22 03:10

rownage