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

3 Answers 3

14

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.

3
  • what about the 0 thing ? where does it came from. thanks again. Jul 16, 2010 at 12:15
  • 1
    Try doing your query again, except say SELECT * FROM users instead of SELECT UID FROM users. the result (say if you have two columns in your table) should be something like this: array 'UID' => string '45' (length=2) 0 => string '45' (length=2) OtherData1 => string '12' (length=3) 1 => string '12' (length=3) Where the third and fourth lines are the second column (the names and values are just made up by me) And there wouldn't be a StackOverflow if it weren't for newbie questions ;)
    – rownage
    Jul 16, 2010 at 12:23
  • Thanks a lot for your answer and thanks too for the link, now I know more options to be applied when necessary
    – avolquez
    Mar 6, 2013 at 20:59
2

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

2

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.