Home Ask Login Register

Developers Planet

Your answer is one click away!

Eben Kouao February 2016

Store multiple rows from mysql database into one single variable

this is really hard for me, i'm trying to store multiple rows from my table in mysql into a single variable

$mysql_statementJc = "SELECT * FROM `dog`.`cat` WHERE `name` = '$name'";
$mysql_commandJc = mysql_query($mysql_statementJc);

 while($row = mysql_fetch_array($mysql_commandJc)){

    $followI = $row['industry'];

    $groupConcat = $followI . " OR ";

    echo $groupConcat;

This is my appproach, so at the end of it all i can get "sam, john, bob" saved as $groupConcat which can then be used elsewhere.

Many thanks.


Dagon February 2016

you want to create a concatenated string, php has the .= syntax for this:


 while($row = mysql_fetch_array($mysql_commandJc)){
    $groupConcat .= $row['industry'] . " OR ";
    echo $groupConcat; //no point echoing inside the loop

sometimes a better approach is to use an array and implode()


 while($row = mysql_fetch_array($mysql_commandJc)){
    $groupConcat[] = $row['industry'];
    echo implode(' OR ',$groupConcat);

Patrick Q February 2016

Each time through the loop, add the desired value to an array. Then, after the loop, use the implode() function to create your desired output.

while($row = mysql_fetch_array($mysql_commandJc)){

    $followI = $row['industry'];

    $resultArray[] = $followI;

$groupConcat = implode(" OR ", $resultArray);

echo $groupConcat;

Note that you should really stop using the mysql library and instead use mysqli or PDO.

devpro February 2016

You can also do it as:

$followl = array();

while($row = mysql_fetch_array($mysql_commandJc))
    $followl[] = $row['industry'];

$groupConcat = implode(" OR ",$followl);
echo $groupConcat;

Some Explanation:

Store values into an array $followl and than use implode() function for imploding with OR.

Side note:

Please use mysqli_* or PDO becuase mysql_* is deprecated and no more available in PHP 7.

Post Status

Asked in February 2016
Viewed 1,081 times
Voted 12
Answered 3 times


Leave an answer

Quote of the day: live life