Home > database >  Put all rows from 1 column in 1 varchar
Put all rows from 1 column in 1 varchar

Time:01-29

I have 1 table (in MySQL) with 1 row. The values of that table are for example:

5
24
67

I select the values with this query:

$oudeGetallen = $conn->query("SELECT getal from ingezettegetallen");

Now I would like to put the values of that table in 1 text variable in PHP.

So that $oudeGetallenString = 52467

I cannot manage that. I tried putting it in an array and use implode after that, but that didn't work. Could you please help me?

CodePudding user response:

It is strange to concatenate numeric vales like that, but you can do it with the use of GROUP_CONCAT() aggregate function if you specify the empty string '' as the separator:

SELECT GROUP_CONCAT(getal SEPARATOR '') AS col
FROM ingezettegetallen;

or with an ORDER BY clause:

SELECT GROUP_CONCAT(getal ORDER BY getal SEPARATOR '') AS col
FROM ingezettegetallen;

See the demo.

CodePudding user response:

I am assuming you are using the MYSQLI extension! This you can do in a number of way but a simple one is

$oudeGetallen = $conn->query("SELECT getal from ingezettegetallen");

$oudeGetallenString = '';
while ( $row = $oudeGetallen->fetch_object()) {
    $oudeGetallenString .= $row->getal;
}
echo $oudeGetallenString;

OR

$oudeGetallen = $conn->query("SELECT getal from ingezettegetallen");
$arr = [];
while ( $row = $oudeGetallen->fetch_object()) {
    $arr[] = $row->getal;
}
$oudeGetallenString = implode('', $arr);
  •  Tags:  
  • Related