Re: storing an array in mysql - what's the best data type?
| From: | Steven Jarvis | Date: | Tue, 09 Jul 2002 13:55:41 +0000 |
| Subject: | Re: storing an array in mysql - what's the best data type? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-106357@lists.php.net to get a copy of this message | ||
Kevin,
I have an array that I want to store in a field of a mysql db. I've got it set as type text currently, but when I retrieve it, I can't get the arrary to parse. If I look at the listings in the mysql cli, it just says "Array" for that field. Here's my retrieval code: $storyid = $_REQUEST['storyid']; $db = mysql_connect("localhost", "user", "pass") or die ("Could Not connect to db."); mysql_select_db("storiestest", $db) or die("Could not select database."); $query = "SELECT * FROM ADGstories WHERE (storyid='$storyid')"; $results = mysql_query($query, $db); $num_results = mysql_num_rows($results); for ($i=0; $i < $num_results; $i++) { $row = mysql_fetch_array($results); while ($element = each($row)) { echo $element["key"]; echo ": "; echo $element["value"]; echo "<br>\n"; $varname = $element["key"]; $$varname = $element["value"]; } echo "<h2>$headline</h2>\n <p class='byline'>$byline</p>\n"; // just as a test, not looping through the array. Loop code not included. echo "<p class='bodycopy'>$bodycopy[0]</p>\n"; } Even with the version at the end there, I get "A" echoed to the screen. If I try a print_r($bodycopy), it says "Array". Where did I screw up?
You can store arrays as strings with..Yes. That worked.$str = serialize($ary);.. and turn a serialized string back into an array with..$ary = unserialize($str);The string can be stored in either a TEXT or TINYTEXT field. Is this what you wanted to know?
I had trouble following your code after the for loop. $headline, $byline and $bodycopy are variable names stored in the database?Yes. Sorry about that. I should have explained what those variables were. In any case, your solution worked for me. thanks! Steven -- Steven Jarvis Web Publishing Manager/Web Developer NWAnews.com: Arkansas Democrat-Gazette, Northwest Edition Northwest Arkansas Times Benton County Daily Record