0

I have the following sql that pulls info for a specific user:

public function getForUniqueID($unique_id) {

    $sql = "SELECT `first_name` as first_name, `last_name` as last_name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1";
    $stmt = $this->pdo->prepare($sql);
    $stmt->execute([$unique_id]);

    if ($stmt->rowCount() == 0) return null;

    $tournament = $stmt->fetchAll(PDO::FETCH_NAMED);
    $tournament = $tournament[0];

    $tournament = $this->applyRelations($tournament);

    return $tournament;

}

This returns an array object but I'd like to return the first_name and last_name values as one string in this format: first_name " " last_name

How can I modify the method above to return the first and last name as a single string?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Joe Shmoe
  • 27
  • 5
  • [`implode`](https://www.php.net/manual/en/function.implode.php) the array. – Don't Panic Aug 07 '19 at 21:53
  • 2
    Also, if your query will only return a single row, you can just use `fetch` rather than `fetchAll`. Then you won't need to do `$tournament = $tournament[0]`. – Don't Panic Aug 07 '19 at 21:56
  • 1
    You need to use single quotes in that CONCAT. Your SQL string is already enclosed in double quotes. – Don't Panic Aug 07 '19 at 22:38
  • Doh! Thanks @Don'tPanic! that fixed it – Joe Shmoe Aug 07 '19 at 22:41
  • You're welcome! I think it would be best for you to revert the changes to your question, though. As it is now, it's difficult for anyone else who comes along to see how the answer really answers the question since they both have the same code now. – Don't Panic Aug 07 '19 at 22:46

1 Answers1

2

There are many ways to approach this. The simplest is to just concatenate the fields in the select statement. Instead of

SELECT first_name as first_name, last_name as last_name BTW, those aliases are useless since it is the same as the field name.

Do

SELECT CONCAT(first_name, " ", last_name) as name

This simply concatenates the fields into a single field called name but you can change that alias to anything you want.

RisingSun
  • 1,693
  • 27
  • 45
  • 1
    thank you for your help guys. So it sound like I can scrap all the array lines and then just return it correct? – Joe Shmoe Aug 07 '19 at 22:17
  • 1
    @Joe `$tournament` will still be an array if you do it this way, just an array with one item in it rather than two. If you want to skip all the array stuff, use the `fetchColumn` method instead of `fetch` or `fetchAll`. That will return a string. – Don't Panic Aug 07 '19 at 22:26