MySQL DB multiple data for field - php

Maybe I have never searched in the right place but I often wonder what is the best practice to store multiple data in one field and I have never found an answer that I could use.
Let me be more clear with an example.
Let's say I have a "hobbys" field in a user_table
When the user signup he want to add tennis, video game, and piano to his profile.
Is it better:
To create different fields for every hobby like: hobby_id_1, hobby_id_2, hobby_id_3
Or create a single field called hobbys and insert data separated with a comma ? hobbys_id => 1,4,5
(is this solution is actually possible ?)
And then when we want to update those data and add a new hobby for example, how do we do that ?
Any small help would be greatly appreciated.
Thank you in advance :)

This falls under many to many relationship.
For storing many-to-many relationships, an intermediate table that mainly stores the primary keys (IDs) of each relationship is required. In your case,
users_table(user_id, firstname,...)
hobbies_table(hobby_id, name,...)
users_hobbies_table(id, user_id, hobby_id)
Here is a more elaborate explanation.

Related

MySql multiple tables or one big table?

I am currently making an agency CMS and would like to ask about user details.
So the registration form is split to 2 groups, Photographers and Models.
Models can select options about their body type, suc as Hair color, Hair Lenght, Height and other, but these options are not needed for photographers.
My question is, wich is more effective? Storing everything in a big table or spliting the body detalis.
Example
users_table <--- contains everything
or
users_table <--- containing login details and a few basic information
users_body_table <--- containing model body information
If someone could give me some info about this would be happy
thank you folks
From your description I would definitely recommend going with second approach - splitting the data.
You should notice that in the first approach you will have roughly one quarter of the table filled with nulls.
About nulls effect you can see for example here
The most important thing that will determine which is more efficient is how much you will need only get Photographers or only Models. For me it's quite clear that probably often - and because of that, with split table it will be better.
And maybe if you will meet some need of changes, it will be easier to maintain to change it for only one table (if for example some new Model trait will be added).
Think in terms of future normalization
With a splitted tables you can easily run through one table if you want just retrieve data on this.
If your big table have a lot of data the time of retrieving will be too much. if you map the table to object it is better to have a small object. you can reuse it too.... Maybe you can use view if you want really one table (view is a transparent dynamic table)
Good way is separate tables.
One table for common details (users) (login, password, etc)
Second table for models (users_models) and 3rd table for photographers (users_photo)
In table users you can make 2 fields for store id from models and photo tables. In this case one user can be model or/and photographer.

Find the underlying field from a query/view field

Why?
I am trying to dynamically find where foreign keys points. For this I search in information_schema.KEY_COLUMN_USAGE. It works fine for tables, but not for views.
Views are referenced in information_schema.VIEWS, the view_definition field exposes the query.
I think that this is the only place I will find information about where view fields comes from, right?
Then, I would search for my field name between the SELECT and the FROM. If it is an alias, get the table field name and the table name (and resolve the table if it is an alias).
Last complication, the view can refer to another view, then the code will have to be recursive.
Let's take an example (view name is vw_mandates_articles):
select ma.*, a.id_articles_unit, a.id_articles_category from mandates_articles ma
left join articles a on ma.id_article = a.id
The way it is stored in the VIEWS table is:
select `ma`.`id` AS `id`,
`ma`.`id_mandate` AS `id_mandate`,
`ma`.`id_article` AS `id_article`,
`ma`.`unit_price` AS `unit_price`,
`ma`.`description` AS `description`,
`a`.`id_articles_unit` AS `id_articles_unit`,
`a`.`id_articles_category` AS `id_articles_category`
from (`ste`.`mandates_articles` `ma`
left join `ste`.`articles` `a` on((`ma`.`id_article` = `a`.`id`)))
my inputs are:
the view name (vw_mandates_articles)
the field name (id_articles_category)
the expected output:
the field table (ste.articles)
the field name (id_articles_category) //could be same as input but not necessarily
I am not asking someone to write it for me, I just want to validate the approach before digging.
Any thoughts? Good/bad approach, alternatives?
Thanks in advance for your lights
Yes. Views only have fields stored in the query in the information_schema.VIEWS table.
No there's no better way than exploding etc. in the query...
I wouldn't recommend to make recursive views. What's sure is that it'll be slow (mysql will have to store the temporary result(s) on the hard disk what's really not improving performance).
Even if it isn't best practice, I'd tend to increase redundancy and get the data by using one single query (with maximal 1 subselect).

MySQL database optimization for 20.000 users or more

I have been looking for some optimization tips since I´m doing a RPG modification which uses MySQL to store data by PHP.
I´m using one unique table to store all user information in columns by his unique ID, and I have to store (many?) data for each user. Weapons and other information.
I´m using explode and implode as a method to store the weapons, for example, in one column with the 'text' value. I don´t know if that´s a good practice and I don´t know if I will have performance problems if I get thousands of players doing tons of UPDATES , SELECT , etc, requests.
I read that a Junction table may be better to store the weapons and all those information, but I don´t know if that will get better information that you request it by the explode method.
I mean, I should store all the weapons in a different table, each weapon with his information (each weapon have some information, like different columns, I use multiple explode for that inside the main explode) and the user owner of that weapon to identify the weapon than just have them in one column.
It can be 100 items at least to store, I don´t know if it´s good to make 100 records per user on a different table and call all of them all the time better than just call the column and use explode.
Also I want to improve my skills and knowledge to make the best performance MySQL database I can.
I hope somebody can tell me something.
Thanks, and sorry for my stupid english grammar.
It is almost always best practice to normalize your table data. There are some exceptions to this rule (especially in very high volume databases), but you probably do not need to worry about those exceptions until you get to the point of first understanding how to properly normalize and index your tables.
Typically, try to arrange your tables in a way that mimics real-world objects and their relations to each other.
So, in your case you have users - that is one table. Each user might have multiple weapons. So, you now have a weapons table. Since multiple different users might have the same weapon and each user might have multiple weapons, you have a many-to-many relationship between them, so you should have a table "users_weapons" or similar that does nothing but relate user id's to weapon id's.
Now say the users can all have armor. So now you add an armor table and a users_armor table (as this is likely many-to-many as well).
Just think through the different aspects of your game and try to understand the relationships between them. Make sure you can model these relationships in database tables before you even bother writing any code to actually implement the functionality.
Yes it is better to use several tables instead of one. It's better to db performance, easier to understand, easier to maintain and simplier to use as well.
Let's suggest that one user has several weapons with multiple features(but not unique among all weapons). And in one place in your game you just need to know the value of one specific feature:
doing it by your way you'll need to find user row in users table, fetch on column, explode it several times, and there you have your value, but it complicates even more if you want to change it and save then.
better way is having one table for user details(login, password, email etc), another table which keeps user weapons(name of weapon, image maybe) and table in which will be all features, special powers of weapons kept. You could keep all possible features of all weapons in extra table as well. This way you if you already know user id from user table, you'll have to only join 2 tables in your sql query, and there you got value of feature of specific weapon of user.
Example pseudo schema of tables:
users
user_id
user_name
password
email
weapons
weapon_id
user_id
weapon_name
image
weapons_features
feature_id
weapon_id
feature_name
feature_value
And if you really want to use some ordered data in text field in database encode it to JSON or serialize it. This way you don't have to explode and implode it!
As all guys said, typically you should start from normalized database structure.
If performance is ok, then great, nothing to do.
If not, you can try many different things:
Find and optimize query which works slow.
Denormalize queries - sometimes joins kill performance.
Change data access pattern used in application.
Store data in file system or use NoSQL/polyglot persistence solution.

DB Design - Suggestions

i really confused what to do and need your suggestions for my DB Design.
First of all,
As you see in the table, i have id,name,eventCategory,totalEvents and date . This table name is InitPlayer. InitPlayer is an eventAction and i have 3 more eventAction.
As you see in the table, eventCategory items always repetated because dates are changed.
First i though that i keep eventCategory as a table and retrieve items according to them.
What is your DB design suggestions acccording to this picture?
Thank you
Lastly,
I think you should normalize the crap out of your database.
If you're continually reusing the same eventCategory items, you should make a little table, store their names in there, eventCategories, with eventCategory_id and eventCategory_title fields (or something similar), then just reference the ID of said eventCategory in the initPlayer table or create a table to references both initPlayer IDs and eventCategories IDs.
Normalizing and separating will help you to maintain order within your database and help keep you sane. You'll have a little more work with your queries, but it's worth it if you want to scale, or say, change the name of a specific eventCategory.
First i though that i keep eventCategory as a table and retrieve items according to them.
Hold that thought, and do it. Then create a UserInitEventCategory table, where you link userInit.ID to eventCategory.ID.

How do I use PHP, JS and HTML to appropriately handle many-to-many relationship?

Thank you in advance for your help!
I have a large and complicated form with several many-to-many relationships that I'm struggling to deal with. I have, after A LOT of encouragement, created the two appropriate tables for each of those relationships (e.g. one table cars filled with carID's and carName's, and an intersecting table userCars that stores userID's and carID's), no matter the size.
My question is: should my form HTML always be generated by PHP based on those tables? For example, should I have PHP check the cars table and generate one check-box for each row in the table, even though I'll only be starting with five? Is there a better way of doing this besides calling a PHP function onLoad and having that function call a javaScript function?
Also, after the user has submitted the form, how do I store those values? Do I need to go through each POST variable name and compare them to each carName in the table cars in order to get the carID associated with that name, and then make an entry in the userCars table? Or should I just say "if Volvo, carID = 4" because I only have five cars right now!
Again thank you for all of your advice! I would have been totally stuck several times without your generosity!
I agree with Marek that as soon as a php application becomes a litlle bit complicated you are better off with a framework. Preferably one like yii which offers a many-to-many ORM.
That said one of the mistakes a lot of coders make early on is to make a form too complicated.
A good question to ask yourself is whether this form is trying to do too much. It's hard to make a judgement without seeing a link to the actual form.
One way to tackle a problem like this would be to use javascript (jquery:ajax) to update the join table as the user selects a car so that when you submit the form you are only updating the values of the main table.
So a form might look like
Your Name __
Your Age __
Your Favourite Colour __
Cars You have owned
Volvo _ Ford _ Fiat_ Mercedes _
{... these values could dynamically created from an options table ...}
{using jquery each value selected/unselected sends an ajax post to update your user_cars table}
When form is submitted only the user table is updated
However you could also loop through the values of $_POST['cars'][] to update the user_cars table here as well. Which is probably the better solution.
You should make your HTML generated by your database values, or you should make some Javascript that fetches the values from the database, and sets the value in the page based upon those values. Secondarily, if you set the IDs of the form elements to the IDs of the associated entries in the database, then you should just be able to update the database from the set of IDs that were included in the POST.

Categories