fishcracker
fishcracker

Reputation: 2529

combine result in MySQL

I have this query:

$query = 
         "
         SELECT
           detail_firstN AS firstname,
           detail_lastN AS lastname
         FROM users
         WHERE
           users_id = :users_id
         ";

The result will be something like this:

Array
(
    [firstname] => John
    [lastname] => Doe
)

Is there any way in MySQL that I can combine the result for me to have only this output?

Array
(
    [name] => John Doe
)

Upvotes: 1

Views: 72

Answers (2)

Temüjin
Temüjin

Reputation: 15558

Try this code

<?PHP

function combine_result($array,$out_key = "name") // Deafult output key is [name]
{
    if(is_array($array))
    {
        $vals = array_values($array);
        $out  = implode(" ",$vals);
        return array($out_key=>$out);
    }
}


$array = array(
                "firstname" => "John",
                "lastname" => "Doe" );


print_r(combine_result($array)); // Array ( [name] => John Doe )


?>

Upvotes: 1

John Woo
John Woo

Reputation: 263913

use CONCAT

SELECT CONCAT(detail_firstN, ' ', detail_lastN) AS Name
FROM   users
WHERE  users_id = :users_id

or CONCAT_WS

SELECT CONCAT_WS(' ', detail_firstN, detail_lastN) AS Name
FROM   users
WHERE  users_id = :users_id

UPDATE 1

Upvotes: 7

Related Questions