MySql multiple tables or one big table? - php

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.

Related

MySQL DB multiple data for field

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.

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.

Many types of data - One table vs multiple tables

I am working on a webapplication, which main functionality will be to present some data to user. However, there are several types of these data and each of them have to be presented in a diffrent way.
For example I have to list 9 results - 3 books, 3 authors and 3 files.
Book is described with (char)TITLE, (text)DESCRIPTION.
Author is described with (char)TITLE, (char)DESCRIPTION.
File is described with (char)URL.
Moreover, every type has fields like ID, DATE, VIEWS etc.
Book and Author are presented with simple HTML code, File use external reader embed on the website.
Should I build three diffrent tables and use JOIN while getting these data or build one table and store all types in there? Which attitude is more efficient?
Additional info - there are going to be really huge amounts of records.
The logical way of doing this is keeping things separate, which is following the 3NF rules o the database design. This gives more flexibility while retrieving different kinds of results specially when there is huge amount of data. Putting everything in a single table is absolutely bad DB practice.
That depends on the structure of your data.
If you have 1:1 relationships, say one book has one author, you can put the records in one row. If one book has several authors or one author has several books you should set up seperate tables books and authors and link those with a table author_has_books where you have both foreign keys. This way you won't store duplicate data and avoid inconsistencies.
More information about db normalization here:
http://en.wikipedia.org/wiki/Database_normalization
Separate them and create a relationship. That way, when you start to get a lot of data, you'll notice a performance boost because you are only calling 3 fields at a time (IE when you are just looking at a book) instead of 7.

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.

How to store multi-valued profile details?

I have many fields which are multi valued and not sure how to store them? if i do 3NF then there are many tables. For example: Nationality.
A person can have single or dual nationality. if dual this means it is a 1 to many. So i create a user table and a user_nationality table. (there is already a nationality lookup table). or i could put both nationalities into the same row like "American, German" then unserialize it on run-time. But then i dont know if i can search this? like if i search for only German people will it show up?
This is an example, i have over 30 fields which are multi-valued, so i assume i will not be creating 61 tables for this? 1 user table, 30 lookup tables to hold each multi-valued item's lookups and 30 tables to hold the user_ values for the multi valued items?
You must also keep in mind that some multi-valued fields group together like "colleges i have studied at" it has a group of fields such as college name, degree type, time line, etc. And a user can have 1 to many of these. So i assume i can create a separate table for this like user_education with these fields, but lets assume one of these fields is also fixed list multi-valued like college campuses i visited then we will end up in a never ending chain of FK tables which isn't a good design for social networks as the goal is it put as much data into as fewer tables as possible for performance.
If you need to keep using SQL, you will need to create these tables. you will need to decide on how far you are willing to go, and impose limitations on the system (such as only being able to specify one campus).
As far as nationality goes, if you will only require two nationalities (worst-case scenario), you could consider a second nationality field (Nationality and Nationality2) to account for this. Of course this only applies to fields with a small maximum number of different values.
If your user table has a lot of related attributes, then one possibility is to create one attributes table with rows like (user_id, attribute_name, attribute_value). You can store all your attributes to one table. You can use this table to fetch attributes for given users, also search by attribute names and values.
The simple solution is to stop using a SQL table. This what NoSQL is deigned for. Check out CouchDB or Mongo. There each value can be stored as a full structure - so this whole problem could be reduced to a single (not-really-)table.
The downside of pretty much any SQL based solution is that it will be slow. Either slow when fetching a single user - a massive JOIN statement won't execute quickly or slow when searching (if you decide to store these values as serialized).
You might also want to look at ORM which will map your objects to a database automatically.
http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#PHP
This is an example, i have over 30
fields which are multi-valued, so i
assume i will not be creating 61
tables for this?
You're right that 61 is the maximum number of tables, but in reality it'll likely be less, take your own example:
"colleges i have studied at"
"college campuses i visited"
In this case you'll probably only have one "collage" table, so there would be four tables in this layout, not five.
I'd say don't be afraid of using lots of tables if the data set you're modelling is large - just make sure you keep an up to date ERD so you don't get lost! Also, don't get caught up too much in the "link table" paradigm - "link tables" can be "entities" in their own rights, for example you could think of the "colleges i have studied at" link table as an "collage enrolments" table instead, give it it's own primary key, and store each of the times you pay your course fees as rows in a (linked) "collage enrolment payments" table.

Categories