How to store a array in a database? - php

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.

Related

How do obfuscate JSON response when dealing with a DB query?

[
{
"businesscards_id":"12",
"X_SIZE":"1.75x3",
"X_PAPER":"14ptGlossCoatedCoverwithUV(C2S)",
"X_COLOR":"1002",
"X_QTY":"250",
"O_RC":"NO",
"F_PRICE":"12490",
"UPS_GROUND":"12000",
"UPS_TWODAY":"24000",
"UPS_OVERNIGHT":"36000"
}
]
This JSON encode response is seen in console of Chrome. This array is being returned from a DB query. It is showing my table column names. For security reasons I do not want to show my table column names. How can this JSON object be obfuscated or hashed and/or encoded or dynamically re-written to keep my table col names private?
Don't do anything to your JSON.
If you don't want your column names to be visible, just dont use your column names. Create a new array using new keys to send with JSON and then change that array back into one containing your column names afterwards.
But it really shouldn't be a problem people seeing them. Nobody has access to your database so letting people see column names isn't an issue.
It really depends on how you wish to use the record once it has been received. One strategy might be to return an array of the values only, discarding the keys. Then in your code, use your private knowledge of which array value you need when you process the record. Something like:
var result=[];
Object.keys(record).forEach(function(key){result.push(record[key]);});
And then in your code, use array indices to access the values.
SQL statement:
SELECT `col_name` AS 'something_else'
But also, as everyone else said, don't do this for security. It is pointless.

How to handle an array in a SQL field?

I have a feed that comes from the State of Florida in a CSV that I need to load daily into MySQL. It is a listing of all homes for sale in my area. One field has a list of codes, separated by commas. Here's one such sample:
C02,C11,U01,U02,D02,D32,D45,D67
These codes all mean something (pool, fenced in area, etc) and I have the meanings in a separate table. My question is, how should I handle loading these? Should I put them in their own field as they are in the CSV? Should I create a separate table that holds them?
If I do leave them as they are in a field (called feature_codes), how could I get the descriptions out of a table that has the descriptions? That table is simply feature_code, feature_code_description. I don't know how to break them apart in my first query to do the join to bring the description in.
Thank you
As a general rule, csv data should never stored in a field, especially if you actually need to consider individual bits of the csv data, instead of just the csv string as a whole.
You SHOULD normalize the design and split each of those sub "fields" into their own table.
That being said, MySQL does have find_in_set() which allows you sort-of search those csv strings and treat each as its own distinct datum. It's not particularly efficient to use this, but it does put a bandaid on the design.
You should keep the information about feature codes in a separate table, where each row is a pair of house identifier, and feature identifier
HouseID FeatureID
1 C07
1 D67
2 D02
You can use explode() to separate your CSV string : http://php.net/manual/en/function.explode.php
$string = 'C02,C11,U01,U02,D02,D32,D45,D67';
$array = explode(',', $string);
Then with your list of feature_codes you can easily retrieve your feature_code_description but you need to do another query to get an array with all your feature_codes and feature_code_description.
Or split your field and put it in another table with the home_id.
You can save it in your DB as is and when you read it out you can run the php function explode. Go check that function out. It will build an array for you out of a string separating the values by whatever you want . In your case you can use:
$array_of_codes = explode(",", $db_return_string);
This will make an array out of each code separating them by the commas between them. Good luck.

Insert an array in MySQL database

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!

Using explode, split, or preg_split to store and get multiple database entries

I'm trying to figure out how and which is best for storing and getting multiple entries into and from a database. Either using explode, split, or preg_split. What I need to achieve is a user using a text field in a form to either send multiple messages to different users or sharing data with multiple users by enter their IDs like "101,102,103" and the PHP code to be smart enough to grab each ID by picking them each after the ",". I know this is asking a lot, but I need help from people more skilled in this area. I need to know how to make the PHP code grab IDs and be able to use functions with them. Like grabbing "101,102,103" from a database cell and grabbing different stored information in the database using the IDs grabbed from that one string.
How can I achieve this? Example will be very helpful.
Thanks
If I understand your question correctly, if you're dealing with comma delimited strings of ID numbers, it would probably be simplest to keep them in this format. The reason is because you could use it in your SQL statement when querying the database.
I'm assuming that you want to run a SELECT query to grab the users whose IDs have been entered, correct? You'd want to use a SELECT ... WHERE IN ... type of statement, like this:
// Get the ids the user submitted
$ids = $_POST['ids'];
// perform some sanitizing of $ids here to make sure
// you're not vulnerable to an SQL injection
$sql = "SELECT * FROM users WHERE ID IN ($ids)";
// execute your SQL statement
Alternatively, you could use explode to create an array of each individual ID, and then loop through so you could do some checking on each value to make sure it's correct, before using implode to concatenate them back together into a string that you can use in your SELECT ... WHERE IN ... statement.
Edit: Sorry, forgot to add: in terms of storing the list of user ids in the database, you could consider either storing the comma delimited list as a string against a message id, but that has drawbacks (difficult to do JOINS on other tables if you needed to). Alternatively, the better option would be to create a lookup type table, which basically consists of two columns: messageid, userid. You could then store each individual userid against the messageid e.g.
messageid | userid
1 | 1
1 | 3
1 | 5
The benefit of this approach is that you can then use this table to join other tables (maybe you have a separate message table that stores details of the message itself).
Under this method, you'd create a new entry in the message table, get the id back, then explode the userids string into its separate parts, and finally create your INSERT statement to insert the data using the individual ids and the message id. You'd need to work out other mechanisms to handle any editing of the list of userids for a message, and deletion as well.
Hope that made sense!
Well, considering the three functions you suggested :
explode() will work fine if you have a simple pattern that's always the same.
For instance, always ', ', but never ','
split() uses POSIX regex -- which are deprecated -- and should not be used anymore.
preg_split() uses a regex as pattern ; and, so, will accept more situations than explode().
Then : do not store several values in a single database column : it'll be impossible to do any kind of useful work with that !
Create a different table to store those data, with a single value per row -- having several rows corresponding to one line in the first table.
I think your problem is more with SQL than with PHP.
Technically you could store ids into a single MySQL field, in a 'set' field and query against it by using IN or FIND_IN_SET in your conditions. The lookups are actually super fast, but this is not considered best practice and creates a de-normalized database.
What is nest practice, and normalized, is to create separate relationship tables. So, using your example of messages, you would probably have a 'users' table, a 'messages' table, and a 'users_messages' table for relating messages between users. The 'messages' table would contain the message information and maybe a 'user_id' field for the original sender (since there can only be one), and the 'users_messages' table would simply contain a 'user_id' and 'message_id' field, containing rows linking messages to the various users they belong to. Then you just need to use JOIN queries to retrieve the data, so if you were retrieving a user's inbox, a query would look something like this:
SELECT
messages.*
FROM
messages
LEFT JOIN users_messages ON users_messages.message_id = messages.message_id
WHERE
users_messages.user_id = '(some user id)'

Get content from string in different situations

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

Categories