storing post information in mysql as array
How would i go about taking all information thats submitted via POST to a page, and storing it in a db as a readable array
Right now i have this function:
$mysql = mysql_query("INSERT INTO `table` (`sid`, `contents`) VALUES ('$sid', '$contents')") or die(mysql_error());
if($mysql){
return TRUE;
}else{
return FALSE;
}
when i pass $_POST for $contents, all i get in the db is Array
I need some way of reading the post values, converting开发者_如何学Python them to something readable, storing them, and then being able to get them back out and loop through the info again
Although you can serialize an array and store it in a MySQL field, I wouldn't recommend going about it this way. You don't expose what you are trying to achieve in your question, but I think you're just starting out using MySQL.
The way that I'd recommend is just designing a proper table with columns named after the values you wish to store, and then to create a proper query to store the values separately, not as a big serialized array.
Here's a crash course: http://www.oreillynet.com/pub/a/php/2003/12/23/php_foundations.html
Use serialize
:
Generates a storable representation of a value This is useful for storing or passing PHP values around without losing their type and structure.
Example:
// turn $_POST into a string that can be reconstructed to its original array form
$postStr = serialize($_POST);
Use unserialize
to recover the string as an array:
// give me back my array
$postArr = unserialize($postStr);
Make sure to correctly escape your string using mysql_real_escape_string
prior to inserting in the database.
You need to serialize http://php.net/manual/en/function.serialize.php and then store the POST data.
To fetch it you need to unserialize it after fetching
+1 to nash. What you want to achieve is against the database normalization. You may think that it's a good idea now but you'll feel remorse soon. If you're unconfortable with the database level, you could try a ORM.
精彩评论