How do we store arrays in database?
What I am doing is the following:
// $data is an array
$v = base64_encode(json_encode($data));
$todo = 'INSERT INTO table (data) VALUES("' . $v . '")';
$sql = mysql_query($todo);
Also why do I have to call base64_encode before I store the array in the database?
What you are doing is possibly wrong. There are many decisions you have made that are not by any means necessary, and they may also not be appropriate.
For one thing, storing “frozen” arrays in the database is usually a bad idea because you cannot do anything with them other than get them back (you cannot modify them or query based on their contents). Solutions that “fix” this issue are database-oriented and include changing your table schema. I don’t know what you are trying to do so I won’t go in more detail.
Then, if you do want to serialize arrays in your database (there are legitimate use cases) (edit: and only intend to access them through PHP code — as was very correctly pointed out!), the only thing you should be using is the
serializefunction — notjson_encodeor anything else. This is the very reason that function exists. When you get the values back from the database, usedeserializeto get the array back.Finally, when injecting a variable into an SQL query, you need to escape it with
mysql_real_escape_string(which you are not doing).So it would be much better to do: