Problem getting text field as string from MySQL with PHP

I'm having this problem that's driving me nuts.

I've got a MySQL database in which there is a table that contains a text field. I am querying the table in PHP and trying to put the content of the text field for each row into a var.

I am doing something like this:

for ($i=0;$i<$nbrows;$i++){
  $id = $data[$i]['ID'];
  $description = $data[$i]['DESCRIPTION'];
  $mystring .= '<div>'.$id.': '.$description.'</div>';

DESCRIPTION is my text field.

I'll pass on the details. The $data array is built from mysql_fetch_array($result). I also tried using objects instead, as I use mysql_fetch_object for all my other routines, but there is no change.

Anyway, the problem is this: if I do "echo $description;" then it works. I am getting my text field data as expected. The problem is that I don't want to output it directly, but add it to a concatenated string, and that is not working. What happens in that case is it seems to be taking $description for some kind of array or object. To make the above example work, I have the replace the string with:

$mystring .= '<div>'.$id.': '.$description[0].'</div>';

So in the concatenated string code, if I treat $description as an array, it works, but obviously I am getting only one letter. (it doesn't actually seem to be an array because I can't implode it).

I tried a million things but I just can't make this work unless I use echo, but that is not what I am trying to do.

There is no issue with fields that aren't text.

Thanks for any ideas!

Asked By: David

Answer #1:

There is nothing visually wrong with the code you pasted, maybe if you could also add the fetching function as well, we might be able to help you further.

Maybe you could post a var_dump of your $data array?

Answer #2:

Have you tried $mystring .= "<div> $id : $description </div>";

Answered By: Aaron Harun

Answer #3:

Ack, well, you know, hours spent on this and then it becomes obvious after I decide to post for help. This is just because of text encoding/escaping and nothing else. I just didn't see well enough where the problem was actually happening.

Thanks for taking the time to read and respond!

Answered By: David
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

# More Articles