Ben Ben - 7 months ago 9
PHP Question

Combine colums into one result

I have a client db and return an adress db record with this statement :

$query = $this->db_connection->prepare('SELECT company, street, etc. FROM clients ');


The result looks like this :

Array (
[0] => Array (
[company] => The one and only company
[street] => Road to heaven 114
[etc.] => ....
[1] => Array (
[company] => Better forever
[street] => Wild west 145
[etc.] => ....
)
)


For a quick overview I generate a php table and print a combined string from
company, street, etc.
into one field.




To make it more simple in php I want to let the job be done by
mySQL
.
The PDO prepare statement looks like this:

$query = $this->db_connection->prepare('SELECT company +", "+ street as adress FROM clients ');


But the result contains weired numbers, not what I expected.

Array (
[0] => Array (
[adress] => 0
)
[1] => Array (
[adress] => 6
)
[2] => Array (
[adress] => 15
)
)


What do I do wrong ?

Answer

You shouldn't use + to concatenate different fields, as it will then become a mathematical expression. + is the arithmetic operator for addition, that's why it is returning numbers.

You're looking for the CONCAT (or alternatively the CONCAT_WS) function, like this:

SELECT CONCAT(`company`, ", ", `street`) AS `address` FROM `clients`;

That should return:

['address'] => 'The one and only company, Road to heaven 114'