0

I have a column of data from an SQL database which I am calling through PHP. I wish to convert these results in to a consecutive string. So, it's a case of converting the result (consisting of a series of strings from the columns) in to a string.

How would I go about this?

At the moment, when I print the data using

while($row = mysqli_fetch_array($result))
  {   
  echo  $row['title'];
  echo "<br>";
  }

it returns each item, but I wish to place these items into a string.

Thanks

3 Answers 3

3

You can do that using the implode-function:

$titles = array();
while($row = mysqli_fetch_array($result))
{
    $titles[] = $row['title'];
}
$titlestring = implode(",", $titles);

An other option would be to concatenate the strings yourself like this:

$titlestring = "";
while($row = mysqli_fetch_array($result))
{
  $titles .= $row['title'] . ", ";
}
$titlestring = substr($titlestring, 0, -2);

The first option is better though in my opinion.

Sign up to request clarification or add additional context in comments.

1 Comment

The second option is just so very very unpleasant, and I see far too many programmers do it. The first one is the only one that makes sense.
0
while($row = mysqli_fetch_array($result))
{    
    $myString .=  $row['title'] . " ";
}

3 Comments

In PHP you don't do string concatenation with a +.
@PatrickKostjens : I edited my answer, but + works well as I remember.
No it doesn't. In a PHP shell you can try echo "a" + "b";. It will result in 0. echo "a" . "b"; will result in ab. What is the + at the end of the line doing there?
0

MySQL can handle this much better..

Give a index on the title column and run a query like this.

SET SESSION group_concat_max_len = @@max_allowed_packet;  

SELECT GROUP_CONCAT(title) FROM database.table GROUP BY title ASC

example returned data title1,title2,title3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.