Best approach to add multiple data to a column in MySQL - php

For example, I have Users and Projects tables.
Multiple users can be members of a project. How do I insert multiple users into the members column of the Projects table?
Do I separate by comma like: "John, Alex, Hanna"?
I'm a beginner in MySQL, sorry if this is a dumb question. Thanks!

You defiantly need another table.
It should look like this
Name: UserProjects
Field: UserId
Field ProjectID
Those 2 fields should be primary keys (dual primary id). If you want to go down the route of 'soft deletes' then add a status column which you'll set to 0 if you delete it. Also look up insert on update for mysql.
Trust me this is the way to go. Using a delimiter field or something will only give you problems later down the line.

Related

How to update specific row in MYSQL

I have a table, where I store user uploaded files. There can be 5 different file types: profile picture, cpr file, degree file, video file, background check file.
Table structure is this:
file_id, user_id, file_type, file_size, file_name, file_new_name, file_path, file_cat, date_created
My questions:
Is this structure efficient or should I create 5 different tables?
If I would like to update, lets say user profile picture row, then what would be the best way to do it? --- I came up with a solution that probably is not be the best one- I update the row where file_cat = "profile_picture" and user_id=:user_id. Would that put a lot of load in the system?
First when user signs up, he doesn't have any files. Should I user insert into ... VALUES ... on duplicate key update with a hidden value in a form?
Thank you in advance.
This is three questions not one.
Is this structure efficient or should I create 5 different tables?
One table is good enough
If I would like to update, lets say user profile picture row, then
what would be the best way to do it? --- I came up with a solution
that probably is not be the best one- I update the row where file_cat
= "profile_picture" and user_id=:user_id. Would that put a lot of load in the system?
Not if you have an index on file_cat, user_id (composite index on both fields). If you want to make things a bit leaner you can store constants instead of 'profile_picture' etc. eg
profile_picture = 1
cpr = 2
....
background = 6
This would make the tables and indexes a bit smaller. It might make the queries slightly faster.
First when user signs up, he doesn't have any files. Should I user
insert into ... VALUES ... on duplicate key update with a hidden value
in a form?
No need for that. not having a record for new users actually makes things easier. You can do an COUNT(*) = 0 query or better still an EXISTS query without having to fetch rows and examine them.
Update:
These EXISTS queries are really usefull when you are dealing with JOINs or Sub Queries for example to quickly find if a user has uploaded a profile picc
SELECT * from users WHERE exists (SELECT * from pictures where pictures.user_id = users.id)
If you use the primary key properly then your insert ... on duplicate key update ... query will do everything for you.
For your table you need to define a primary key column. In this case I would say it is your file_id column. So if you do your insert, the MySQL server will check to see if your file_id column is defined already for that value, if so it will update with the new values, other wise it will add a new row of data with the new file_id.
I should be easy enough to separate it though, make 1 script for creating new rows and another for updating. Usually you will know when you are creating as opposed to updating in an application. Again using a primary key correctly will help you out a lot. Using a primary key in your where clause I am pretty sure is one of the most efficient ways to update.
https://dev.mysql.com/doc/refman/5.5/en/optimizing-primary-keys.html

Insert INTO queries using WHERE clause

I have issue on INSERT INTO query,
In the registration form, when user enter username and select the department/center as bursary,
I want to insert that UserName into table bursary.
What I tried is;
$query14 = "INSERT INTO bursary (UserName) VALUES
('$UserName') WHERE DepartCent='Bursary'";
$result14=mysql_query($query14);
My table name is bursary, and it's look like ;
UserID UserName
1 ( ) <---- I want only UserName that choose department/center as bursary
Please anyone help me to solve this, appreciate that.
INSERT queries imply adding data that isn't there already. If you want to insert a value derived from a query you need to use an actual query to get it. The WHERE clause fails because there no row to examine until you insert one.
There's really not enough info to figure out what you're trying to do, but if we just go on this part of your question:
"I want only UserName that choose department/center as bursary"
Then you are probably looking for an INSERT..SELECT (assumes you have already inserted the data into some other user table 'your_user_table')
INSERT INTO bursary(UserName)
SELECT UserName from your_user_table
WHERE DepartCent='Bursary';
You can either:
insert new rows in a database table
update existing rows in a database table
Only when you are trying to change values of existing rows does it make sense to specify a WHERE clause to let the database know which values you want to change.
EDIT: Could you explain again what it is exactly that you are trying to achieve? Do you want to insert only some users filling out your form? Namely those that choose bursary as their department?
Why don't you change your table structure to something like:
Table DEPARTMENT:
Department Name, Department ID
Table USER:
User Name, Department ID (foreign key to Department)
EDIT Nr. 2: The way to do that is by normalizing your Table structure. Suppose one of the following things happened:
You want to add an additional department later on - you would not want to create a new table for that every time.
You want to change the name of a department - do you want to rename your tables? change your code,... I doubt that
So the way to go is to design your tables in a way that they separate the different "things" in your program. One type of thing you are working with are departments (bursary,...) another type of thing are Users. As a rough starting point try to make a table for each and try to connect the tables with so called foreign keys. Read it like this:
Every department has a unique department ID
Every User is associated to a department by this users Department-ID
You can then later on join these tables to find out all users of department X,...
Select u.userName,d.departmentName from User u INNER JOIN Department d ON
u.departmentId=d.departmentId
This would show you the names of all your users and their associated departmentName

How to make db table field dynamic

i am creating plugin in wordpress for contact us form and in that i am creating fields(textbox,textarea etc...) dynamically based on my requirement. so there is no fixed number of fields. i am storing dynamically created fields in my db table.
in some project i may require to create 3 fields and some project i may require to create 5 fields.. my dynamic form is working fine...
now my problem is DB. how do i create table to store contact us data? bcz sometimes there might be 3 fields and sometime there might be more than or less than 3 fields..
so my question is how do i make my table schema for this scenario...
suggestion will be highly appreciated...
Thanks in advnce
Change table structure is strongly not suggested, it's bad in performance, and may lost data if you drop a column.
So, the original subject 'make db table field dynamic' is possible but not a good plan, we still have alternative plan:
Store dynamic field in one table column
Find a way to combine your dynamic field to a string, either use a separator, or use json_encode works, if the column is long enough (TEXT --> MEDIUMTEXT), you can have unlimit dynamic field.
Create enough column at beginning
Apearently this not as good as upper plan, but it's easier to understand, and search in these column is easier too.
BTW, Have you considered convert these dynamic column to rows ?
You need to store the information taken from the form in one table field using an array. That way it should not matter how many question there are.
Should be quite simple take a look at php arrays.
You can have a single longtext datatype column in your database table and you just need to serialize your form values and store in the single column.
I agree with the others. Dynamically creating database tables is bad. The database schema should hardly ever change once a project is complete.
One solution is:
If you had a contact with multiple addresses, you create a parent/child relationship as follows. Perhaps you can do something similiar with your situation.
Contact
long contactID primary key
name
addressID
Address
long addressID primary key
long contactID foreign key
streetAddress
CityID
CountryID
i don't think so it's a good idea to do like this... but i am suggesting you this because in your case it might be useful
you can do it by ALTER...
so what you can do is "When you are creating new field dynamically at that time only you can create new column in your table like this...
ALTER TABLE table_name ADD $name(Column name) //$name may be your attribute name <input name="">
and same way when you are deleting your field at that time you can drop your table column
ALTER TABLE table_name DROP $name(Column name) //$name may be your attribute name
here i assumed that you have already created table table_name (without any fields)
hope it may help you

Populating a third table to maintain efficiency

I am currently working on a PHP/MySQL project for an assignment. In studying the efficient design of databases while working on the assignment I notice that in many cases it is good practice to create a third table when working with only two sets of data.
For example, if we have a table for "Students" and a table for "Addresses" it appears to be a good idea to create a third table i.e. "Student_Addresses" since a student can hypothetically have more than one address (separated parents etc.) and a single address can represent more than one student (siblings).
My question is: How do we go about populating that third table? Is there a way that it is done automatically using primary and/or foreign keys?
I've tried Google and my textbook to understand this but I've gotten nowhere. Links to tutorials or articles would be greatly appreciated.
Thanks for your help. I hope the question and example are clear.
n:m or 1:m normalization rule
Option 1:
user table
id
f_name
s_name
......
user address table
id
user_id // this should be index only as foreign keys will allow 1:1 only
address line 1
address line 2
address line 3
address_type (home, office ....)
Option 2:
user table
id
f_name
s_name
......
address table
id
address line 1
address line 2
address line 3
address_type (home, office ....)
user_address table
userId
addressId
according to your description option 2 would be the right solution. After adding the data to user table and address table then you need to add the data to user_address table manually. Some Object relational mapper (ORM) may do add the data to the third table automatically but you need to define the relations. check http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html.
http://docstore.mik.ua/orelly/linux/sql/ch02_02.htm
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p7.php
You can save the data in the third table using triggers when the data is inserted/updated/deleted in your base tables. You can learn more about triggers at
mySQL Triggers
However in your case it would be better if you could write the logic at the application/code level to make an entry in the third table. You can set up foreign key relationships to this table from your base tables so that the data remains consistent.
There is no native method in MySQL to populate Student_Addresses in your situation - you have to take care of entering data (connections) by yourself, but you can use - for example - transactions - see answers in this topic: SQL Server: Is it possible to insert into two tables at the same time?
For taking care of connections consistency - in Student_Addresses make not-null fields for relations to ID from Student and ID from Address, make both of these field as unique key together and use ON UPDATE CASCADE and ON DELETE CASCADE. This will take care of removing records from junction table when removing records from any of two other tables and also won't allow you to add same address to the same student twice.
I don't think data will be populated automatically rather it's responsibility of user to insert data.
I am note sure about PHP but using Hibernate and Java this can be done seemlessly. Since data of Students and addresses could be coming through some web application Hibernate can map java objects to records in table and also populate relationship table.

Inserting an entry in multiple tables in an sql database

I'm creating a game in actionscript that requires the use of an external database to store user details and scores.
This database will contain multiple tables, currently there are two.
My first table contains the headers - ID, email, username, password.
My second table contains the headers - ID, lvl1Score, lvl2Score, lvl3Score.
In my game, when a new user is created it creates an entry in the first table with the ID auto-incrementing.
My question is - Is there anyway to automatically create an entry in my second table with its default values and the same ID when I add to my first table?
I've read about joins, but everything i've read just talks about looking up data over multiple tables.
Also, is my table structure correct in the sence that the ID value can be used using the JOIN keywork to look up an entry from both tables.
I would suggest you to go for triggers.
create or replace trigger trigger_name after
insert on table1
for each row
begin
insert into table2 values(new.id,"value for lvl2score","value for lvl3score");
end
Something like this.
If the tables truly have a one-to-one relation, I would recommend that you simply make one table having all the fields.
Or did you mean this should store multiple scores for each individual user? In this case, you should not insert a default record for the user. Instead, the score.ID field should instead reference user.ID and allow duplicates.
I suggest you to use triggers and for more flexibility create a many-many relationship between "user" and "level", so you will end up with 3 tables:
user
level
user_level (this will contain the foreign keys: user_id, level_id)

Categories