user1260310
user1260310

Reputation: 2227

PHP/MYSQL array storing and retrieval issue

I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)

My code to create the array is as follows:

$str = "one,two,three,four";
$array = explode (",",$str)

I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".

The problem is occurring when I try to retrieve data.

I am retrieving using

while($row = mysql_fetch_array($res)) { 
$array = $row['list']; //that's the field it is stored in 
echo $array; // echoes "ARRAY"

//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.

$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
    echo $val;
} //yields error message improper argument for for each statement

}

Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.

Upvotes: 2

Views: 1291

Answers (3)

cantlin
cantlin

Reputation: 3226

The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.

$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);

Later:

while($row = mysql_fetch_array($res)) {
  $array = unserialize($row['list']);
  var_dump($array);
}

Upvotes: 2

The Alpha
The Alpha

Reputation: 146201

I think you can use serialize and also (if you don't use serialize) if your array string is as follows

$str = "one,two,three,four";

then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like

while($row = mysql_fetch_array($res)) { 
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one

Upvotes: 0

clexmond
clexmond

Reputation: 1549

What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:

$serialized = implode(',', $arrayToStore);

and then store that in MySQL. On its way out then you'll do:

$unserialized = explode(',', $arrayFromMySQL);

Upvotes: 1

Related Questions