I'm thinking of storing data from a form as a string, each answer separated by a pipe. The problem I have is that some answers may come in the form of multiple items. We store the radio button selection along with their corresponding answers e.g.
Question 1 - 1 Answer [A1]
Question 2 - Radio button selected [A2] + 3 form fields
Question 3 - 1 Answer [A3]
So I was thinking of storing the data like:
$str = A1|A2[x,x,x]|A3
The reason I chose to enclose multiple selections in brackets is in order to have it relate to the question.
I think my solution will work but when I come to read the values from the database I'll use Php's explode() to get the values into an array.
E.g. explode("|",$str);
Will give:
array(0=>A1, 1=>A2[x,x,x],2=>A3);
Before developing this, what would be the best way of getting the content of [x,x,x] and separating it from array[1]?
Any suggestion will be much appreciated.
Thanks
Alternatively, rather than having your answers as a string then trying to turn them to an array you could start with them in an array then if you need turn them into a string, so you could have:
$array = array('A1',array(x,x,x),'A3');
Then if you do need it as a string you can call:
$str = serialize($array);
That way, you get a similar method of access to your solution after you have exploded the string, only you don't have to deal with trying to split the A2[1,2,3] string further as you can just check if it's an array instead.
Your approach doesn't provide any benefit and it introduces an unnecessary complexity. Why don't you just use a relational database and store each piece of data a in a separate table row? If you don't have access to MySQL or a similar DBMS, you can always use SQLite.
I think you need to take a look at serialize and unserialize.
You could also store the information as an associative array encoded into json with json_encode() function. Then when you fetch data from the database, you would just do:
$arr = json_decode($value);
http://php.net/manual/en/function.json-encode.php
Related
I am trying to learn php databases and I have a question. How do I store an array in a database? I saw an answer on stackoverflow and there were they doing something with type double and in an other answer they were talking about creating a table for every user but I can't find a solution.
So summarized. I want to store an array in a database. I have acces to phpmyadmin so from there can I set the value type. and I would like to store that array in one column.
Can somebody help me solving the problem?
edit one: The things I want to store are music tags. So in code it would be something like this:
array('pop','rock','country');
I want to store It in one column to make it easy searchable
Rather than storing arrays, try this:
Table 'genres' :
id | name
1 | pop
2 | rock
Table 'songs' :
id | ...
1
Table 'songs_genres' :
song_id | song_genre
1 | 1
1 | 2
And use JOIN's to get the genres for each song (or whatever)
Usually you shouldn't store arrays in a single column in a db. It is preferable to have a table with tags and another one that links your entity with its tags. So, before try to store an array in a table just think if it is really the right thing to do in your specific case (usually not).
If you are sure you want to do that then you have serialize and unserialize functions.
UPDATE (after five years)
serialize and unserialize methods are inherently unsecure and should be avoided. It is preferable to store data in JSON format using json_encode and json_decode.
serialize() is one option here. You can serialize a PHP array into a string to store in the database, and when you return the string from the database you can unserialize() to convert it back from a string to an array.
[ Edit ]
After you've updated the question with an example of the data you plan to store, using a MANY:MANY relationship in the actual database structure is the correct way to go, as mentioned in #Alex M's answer
You can use json_encode to make a json string from the array, like so :
$jsonarray = json_encode($array);
then after retrieving the information you decode it.
$array = json_decode($jsonarray, true); // the true will turn it into an array,
otherwise it's an object.
but I'd advice against it. try making a database which has the proper columns and store your data trough there.
Every user can have one or more music tags. In later time they want to add or remove those tags. If you store all of their tags in one column you are pretty much left with string operation rather than database operation. create new table tbl_user_music_Tags and save each tag along with the user ID. this way you have full flexibility of adding, removing, updating and reading tags for a specific user.
You can store it as an string such as 'rock, pop, foo, ...'.
But if you want to manage tags, i think you should store tags in other table as #Alex M suggested.
I'm new to PHP/MySQL. I want to minimize the number of tables I have so I've been thinking of saving an array of IDs (from checkboxes users tick off) as a string instead of in a separate table. What do you use to format the list of IDs as a string so I can easily parse the IDs for future use in my program?
you can use implode()
and explode for joining the values and separating the values respectively. You can also try serialize() for storing the values. There are a lot of examples in my given links, so they will be helpful for your desirable data format.
Thats not a good idea. I think a 1:N-Relation is the better choice. This givs a better performance and the db supports integrity checks.
So if you want to, you can build a comma-separated list and than use following where-statement:
where CONCAT(',', FIELDWITHIDS, ',') like '%,13,%'
to find datasets that reference the ID 13. Or you have to use explode() and implode() in PHP.
Either comma separated values or php serialize (http://php.net/manual/en/function.serialize.php)
That being said, you lose the benefit of being able to do joins or integrity checks in your DB, so you should generally avoid it.
So, there's a field in the db in which I store serialized arrays.
$array = array('count1' => 10, 'count2' => 20, 'count3' => 4);
serialized:
a:3:{s:6:"count1";i:10;s:6:"count2";i:20;s:6:"count3";i:4;}
Would it be possible to pull count1+count2+count3 using a mysql query? I guess I'm looking for something like php's explode. Pretty sure this can't be done, but I thought I'd ask.
I need to pull the highest count1+count2+count3 rows and return the total count. Looping through each row and unserializing wouldn't work since there are TONS of rows.
If you need to access parts of your serialized data via SQL, you need to store them in separate columns.
While it might be possible to use techniques such as regular expressions to access those three values in this string, it would be extremely slow when used in a WHERE criterion as indexes would be useless - not to mention that it would be a huge mess, way worse than using goto in a programming language.
So the solution is to create a new columns and then iterate over all rows, unserialize them, and store the sum into the new column. That might take a while but you'll only need to it once.
Depending on your application it might be better to create three columns and store each value separately.
I want to insert an array into my MySQL database in the format a,b,c.
`var_dump($pvt_contacts)`
results
array(1) { [0]=> array(2) { [0]=> string(3) "102" [1]=> string(1) "3" } }
I tried
`implode(',',$pvt_contacts)'
but it echos Array not 102,3 as I expected . Please help me
If you just want 102,3, then you're off by one (your pointing to a parent array, and not the elements):
implode(',',$pvt_contacts[0]);
If you're trying to store an array in a DB, I recommend serialize. (despite its prevalence in Drupal, ExpressionEngine, Wordpress, etc. this is not generally the best idea).
If you're trying to sent an array to js, I recommend json_encode.
If you're doing something else I need more information.
It is suggested to use multiple rows to store the data, instead of storing the whole array into it. If you insist, here is the way:
Convert your array to the following format:
[key1]{value1}#[key2]{value2}#.... etc
You can use explode to convert it back to array.
The easiest way should be either serialize() or var_export(). But you should only use those if you do not intend to use the data inside the database in any way. If you want to run e.g. SELECT queries on this array data you should store it in a normalized way.
You should use serialize(), unserialize()
or json_encode() , json_decode()
That would make it easier for you to write , and retreive back original data without the need of parsing your stored data yourself .
Here are some good links to assist you :
Preferred method to store PHP arrays (json_encode vs serialize)
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.serialize.php
You can implode your array into a string then explode it back. Default separator is the ,. If you want to run SELECT queries then you can use the MySQL-specific FIND_IN_SET() function however this whole scenario is not recommened, you should use a normalized way as others suggested above.
One way is to convert array to JSON. It will convert array to string and you will be able to store it.
json_encode,
json_decode;
Anyway, I don't think that this it the right way how to deal with the problem. Say, for example, you would need to store blog entries and tags for them into database.
How you do it know?
Save blog entry and tag into one table, one row. You convert all entries tags and save all into database.
How you should do it?
Make two tables:
entries,
entry_tags;
All info that's related to entry save into entries. For example: title, description.
All tags save into entry_tags. In that table there are id (primary key), entry_id (ID that have relationships with entries ID) and tag that simply holds the name.
I hope this will help you!
One of my fields in my data base is an array which has been converted to a string using the implode() function.
How do I retrieve the contents of this field (LESSONS) from the database and store it to a string when a user entered value is equal to the the value of the field NAME?
Thanks in advance for any help you may be able to provide.
Here you go:
$r = mysql_query('SELECT LESSONS FROM TABLE WHERE NAME=\'user_string\'');
$rows = mysql_fetch_assoc($r);
echo $rows['LESSONS'];
I don't know if I understood your question but... Take a look about Stored Procedures
If you used the implode function to convert your array into a string, then this data has lost any information about the array keys.
As far as you want to convert the data back, use the explode function:
$array = explode(',', $columnData);
But You can therefore not search for array keys within the database.
Next to that, the MySQL database (I assume you're using MySQL) can not search for array keys anyway.
You need to store the data in some other way into the mysql to search for it in an SQL later on.
For example, you can create a table that stores key/value combinations with a grouping index.
However MySQL has some string functions that can help you searching within the (now) string data in the MySQL database.
When searching for a value, before the comparison add a comma at the beginning and one at the end of the string. There is a MySQL string function that can concatenate strings. Then search within that expression for your value with a comma added in front and back as well.
Then you can lookop a single array element within the mysql database. MySQL String Functions.
This is a quick solution only, this won't work on large databases performant. However it might solve your problem w/o changing your database structure.