add array to a field in mysql - php

I have array :
$ids=[123,234,567,8910,11324,1];
how to add this to one field in mysql.
After adding check if this id exists if it does not then add it to the same field.
I am looking at something like this.How do I do that .I really appreciate any help .Thanks in Advance.:
---------------------
| all_blocked_users |
---------------------
| 123,234,567 |
---------------------

Right off the bat, let me tell you that storing CSV values in a database is almost never a good idea! It demonstrates poor database design and bad data integrity. It'll likely cause issues further down the line and make working with the data later much more difficult.
Anyway, that having been said, if you still wish to do this, you can use implode() to conver the array into a string, that can then be inserted into your MySQL database:
$dbString = implode(',', $ids);
It would be much better to store the blocked users in another link table.

Related

How to store a array in a database?

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.

Storing in array or in fields? Which is better? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Today I was working on my website and I asked myself a simple question.
Does storing an array with all informations is better than saving those one in different fields?
For example if I store a word, a password and a number in one field on the database in this way
+-------------+----------------------------------------------------------------+
| Field | Value |
+-------------+----------------------------------------------------------------+
| all | ["test","fa26be19de6bff93f70bc2308434e4a440bbad02","25468684888"] |
+-------------+----------------------------------------------------------------+
Is it better than saving it in this way?
+-------------+------------------------------------------+
| Field | Value |
+-------------+------------------------------------------+
| word | test |
| password | fa26be19de6bff93f70bc2308434e4a440bbad02 |
| number | 25468684888 |
+-------------+------------------------------------------+
I think that the first method is faster than the last one because you need only to SELECT one field and not three or more. What do you think about it?
The second method. By far.
You should never put more than one piece of data into a single column.
A single row of data shuld contain all the information you need:
id name password
1 Fluff itsASecret
2 Flupp Ohnoes
Basically, it has to do with updates, selects, searches and pretty much everything that databases do. They are made to do it on single columns, not little bits of data inside a string.
Taking your example, how do you update the password? How do you put an index on the user ID?
What if you also had a bit of data called "NumberOfVotes" If you had it all in one column in a pseudo-array, how do you get a tally of all the votes cast by all users? Would you REALLY want to pull each entry out into PHP, explode it out, add it to the running total and THEN display how many votes have been cast? What if you had a million users?
If you store everything in a ingle column, you could do a tally really easily like this:
select
sum(NumberOfVotes)
from
yourTableName
Edit (Reply to faster query):
Absolutely not, the time it takes to compelte a query will come down to two things:
1) Time it takes to execute the query
2) Time it takes to return all the data.
In this case, the time it takes to return the data will be the same, after all, the database is returning the same amount of bytes. However, with tables that are properly set up, just FINDING the right data will be faster by orders of magnitue.
As an example of how difficult it would be to simply USE a table that has the various bits of information all mumbled together, try to write a query to update the "number" value in the row that starts with the word "test".
Having said that, there are possibly some potential cases where it can in fact be okay to store multiple "fields" of data in one column. I once saw (and copied) an exceptionally interesting permissions system for users that stored the various permissions in binary and each digit in the number equated to being allowed/not being allowed to perform a certain type of action. That was however one interesting example - and is pretty much what I would call an exception that proves the rule :)
I think that the first method is faster
is your main problem actually. You are comparing solutions from only "is it faster" point of view. While you have no measure to tell if there is any difference at all. Or, if even there is, if such a difference does matter at all. So, the only your reason is a false one. While you completely overlook indeed important, essential reasons like proper database design.
Saving in separate fields is a lot more flexible as you are then able to easily search/manipulate data using SQL queries, whereas if they were in an array you would frequently find yourself needing to parse data outside SQL. Consider the following example:
+-------------+----------------------------------------------------------------+
| Field | Value |
+-------------+----------------------------------------------------------------+
| all | ["1","fa26be19de6bff93f70bc2308434e4a440bbad02","25468684888"] |
+-------------+----------------------------------------------------------------+
Using the above table, you need to find the number field for the user with id 1, however there is nothing to search for, you can't simply to a query for the value 1 somewhere in the all field, as that would find every instance of the number 1!
You'll also encounter this problem when changing data in your DB, as you'll have to get the current array, parse it, change the value, then reinsert it.
Also you'll need to put some form of ID as a field to act as a primary key.
However with separate fields for each value, it's fairly simple:
+-------------+------------------------------------------+
| Field | Value |
+-------------+------------------------------------------+
| id | 1 |
| password | fa26be19de6bff93f70bc2308434e4a440bbad02 |
| number | 25468684888 |
+-------------+------------------------------------------+
SELECT `number` FROM mytable WHERE id = 1
The second option is better because its more readable and maintainable.
If someone who didnt write the code has to maintain it, the first option is terrible.
If you ever need to change a field, or add a field, likewise, the first option is a nightmare.
The second option requires much less work.
Keep it simple!
I think given example is trivial and that's why answer for specific example is 2nd method. But there are time's when first method is far more easy to implement. For example you create pages for website dynamically from admin panel, and in start you don't know all the values that will be used in every page. So you put general options like in 2nd method, and put something like page_data and use it to store serialized object. Now you should use serialized object for data that are not likely to change individually, as they are treated as single piece of data.
In your code you fetch serialized object, do unserialize and use them as normal. This way you can add page specific data that are not generalized for every page, but still the page's are the same.

Serialize vs Implode

What do you think is the better way to go about storing a few image id's inside a record in a MySQL database? It's just the image id's which will be used to fetch the images from a different library.
Do i implode the id's in the record like 1#4#7#9#10#12 or do I just serialize the array and store that? Are there any performance benefits by using the one instead of the other? Stability preferences?
I have just always used implode and explode, never really gave it much thought.
Thanks.
If you don't want to (over?)normalize your tables, and you really just want to store a list of ids then I suggest using a simple comma-separated list, because already MySQL has some functions which can directly deal with comma-separated string values:
FIND_IN_SET:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
SELECT FIND_IN_SET('b','a,b,c,d'); --> 2
CONCAT_WS: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws
SELECT CONCAT_WS(',','First name',NULL,'Last Name'); --> 'First name,Last Name'
Of course, you won't be able to do SQL JOINs, but it still can be helpful.
I would pefer serialize or JSON-encode.
It is more flexible and for example will allow you to add image title and other details there in future...
As far as I know there are not significant differences in this case but implode() is a bit faster since it assumes an array and serialize() does not know what you are passing to it.
EDIT based on OP's comment:
Well all the images are stored in a seperate library table with the title and descriptions and things like that. But yeah I see your point.
In that case is not a good idea so serialize several IDs into a single field. What you need is a *-to-Many relation between your 2 tables. This is the correct way of represent multivalued fields:
+----------------------+
| USER |
+---------+------+-----+
| user_id | name | ... |
+---------+------+-----+
+----------------------+
| USER_PICTURE |
+---------+------------+
| user_id | picture_id |
+---------+------------+
+--------------------------+
| PICTURE |
+------------+-------+-----+
| picture_id | title | ... |
+------------+-------+-----+
My friend, serialization is to obtain a string representation of an object's status. Even if it works i don't think is the best way to do what you want. I would prefer to store a json object with the ids. Because a json object is multiplatform, is a string and is easily readable by a human i think is a good approach.

Edit Mysql in PHP

it is just a simple question but i want to solve it as best as possible.
There will be a table in html, which would be filled with data from a mysql query,
for example:
name | street | zip
What i want is to make this changeable, so that user can directly change the results -> click on save -> Update via mysql.
My plan was now, to display the data in input fields which are named like this:
name_id | street_id | zip_id
By clicking on save i would perform a while-loop to get all names, streets, and zips of the id and perform an mysql update afterwords. I know that this would be possible that way (i already used this 1 time).
But: is there a more easier and better solution for this problem?
BR
If you plan to use javascript this is the way to do it!
I was just working with this a few hours ago.
http://www.jeasyui.com/extension/edatagrid.php
Updating all elements could cause heavy load on your server, depending on the amount of data you have stored. A more performance-friendly solution would be to "save" the row keys of the data that you changed. If you do this, you would only update the rows that actually changed, and not all rows!

Yii - creating a link from data stored in a table

Ive been trying to think of / find a solution to an issue i have. Im creating a menu system for my Yii app but I need to store part of the items need for creating the URL in a table.
I have a table called system_menu_item:
---------------------------------------------------------------------|
item_id | dis_text | action | variables |
---------------------------------------------------------------------|
1 | edit article | document/view | array('id'=>$model->arl_id) |
What i was hoping for was:
$model = SystemMenuItem::model()->findByPk('1');
$url = yii::app()->createUrl($model->action, $model->variables);
This doesn't work.. I tried different ways of doing it all not working. Any ideas?
Thanks
I'm going to guess the issue is that $model->variables evaluates to a string with the value array('id'=>$mode->arl_id).
An ugly (and dangerous!) hack would be to read this in using eval()
A better way would be to probably figure out a different way to store your parameters, and read them into an array after performing your DB query.

Categories