How can I correctly convert data from one MySQL column to an array?

E.g. the string is:

$string = $row['1'].","; 
$array = explode (',', $string); 
echo "$string";  
print_r ($array);

echo "$string"; returns correct results - i.e. something,something_else,something_else1 ...

Now I would like to convert the string it created to an array named $array. But when I explode $string (using comma as the separator because it was present in the original string) it doesn't convert it properly.

Instead of creating standard array where "something" is Array 0, "something_else" is Array 1 and "something_else1" is Array 2, it creates Array where "something" is Array 0, "something_else" is Array 1 BUT "something_else1" is again Array 0 despite it should be Array 2 and it goes on this way for the whole string.

It's driving me crazy! I have no idea where the problem is.

Thanks for any help.

Tomas

    I know you described what you had inside of $string, but could you post it please? Someone may see something that you may be overlooking.

    $string = $row['1'].","; 
    echo $string;
    

      Here's a trick from Welling/Thompson:

      function db_result_to_array($result) {
         $res_array = array();
         for ($count=0; $row = @mysql_fetch_array($result); $count++) {
                 $res_array[$count] = $row;
                 }
         return $res_array;
      }

      Use it (somewhat) thusly:

      // query database for a list of "foo"
      
         # seperate db connect function
         $conn = db_connect();
         $query = "select foo from bar order by baz";
         $result = @mysql_query($query);
         if (!$result)
           die("Invalid query!"); // you'll probably want
      //                     to devise your own error handlers
         $num_results = mysql_num_rows($result);
         if ($num_results ==0)
            die("No records match criteria!");  // ditto
         $foo_array = db_result_to_array($result);

      HTH,

        dalecosp,

        Thanks, it worked!

        Tomas

          Write a Reply...