PHP/MySQL insert into multiple data tables on submit - php

I'm building a web application in work and I have a form where users can register certain types of information.
Username | Password | Company
Now I'm unsure how to approach this. What I want is when the user submits that registration form Username, password and company get written to one data table(user) BUT because Company, in the user data table, is a foreign key reference I need Company to be written to a separate datatable(company) as a Primary Key (and of course username to be written as a FK reference as its a 1 - 1 relationship).
I'm not looking for a coded solution from you guys because I know my PHP and MYSQL I'm just looking for some pseudo code algorithms to get the creative juices flowing!
EDIT: I AM USING POSTGRESQL not MYSQL but I'm pretty sure there's little difference except port numbers and small syntax changes

assume first column is id:
Save Company $mysqli->query("INSERT INTO company VALUES (NULL, '$company_name')";
Get id of this item. $company_id = $mysqli->insert_id;
Save User with this id $mysqli->query("INSERT INTO user VALUES (NULL, '$username', '$password', '$company_id')";
Get user's id $user_id = $mysqli->insert_id;
Update the company with it: $mysqli->query("UPDATE company SET user_id = $user_id WHERE company_id = $company_id)";

Begin to insert your compagny in your table compagny.
Get back the id. (There is a sql requete like LastInsertId)
Insert the user/password/IdCompagny in your table user.
EDIT : some help : http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Some questions:
why is User:Company == 1:1? If I and a coworker join your site, do we need to pretend to work at different places?
if companies can have more than one employee, what kind of validation will you employ to combine variations on company names (e.g. IBM vs International Business Machines)?
what if a user is unemployed?
If Company is a nice-to-know datum rather than a required-or-things-break datum, I'd probably sign up my user first. Then, when the user logs in you can nag them for additional information. This has the added advantage of making user registration less onerous for the user.
A use case:
user submits username and password
filtre input for bad stuff and validate for duplication, suitability
save to db and retrieve user PK
load 'additional info' page and set a session var as a "nag" flag
-if user chooses not to fill out add'l info, nag flag can trigger reminder behaviour
add autocomplete to Company field so that user can use existing Company table entries
process form and save to db
either add company and associate user
or just associate user
unset session nag flag so your website won't continue to nag

Related

Creating an Address book with different users.

I'm trying to make an Address book with different users in which they can log in with their username and password. And they can store the information like contact id, first name, last name, phone etc. I want each user to have his own address book.
Can someone please explain how I create different address book for different users.
Thanks a lot.
Create a database. take a primary id to each user or provide unique id.Then create another table fill the fields that you want(address book).Match the user who logged in and and with that another table(foreign key relationship).
When you login ..it checks with db then allows.After that you have to use insert ,update keywords for further process to put data in db.That particular unique id/primary key is used to fetch the related data(address book fields) of that user.
It is actually not a good question for StackOverflow but I will still roughly explain it to you.
You will need two different tables for this. The first one will be used for login details and the second one will record user's address book.
For example:
Table auth will have 3 columns id, username, password
Table addressBook will have contact id, first name, last name, phone etc and also have one more which will be called userID
Whenever any user eneter the data in addressBook their userID from auth table coloum id will be stored along with it. Now you can display their own data to the users.
If you have anymore question ask in comment here.

How better to create Users table?

I created Users table.
After the user registered, The system enter his address, phone, city and more personal details to Users table.
There is another table, called Contacts, there the user add another people details.
Now, if there is Contacts table, How better to save the personal details of the user in Users table? in one json column that contains all the user personal details, or in normal columns (address, phone, city)?
I just do not want to happen a situation of multiple data.
I think separate columns for each field will be the better option!
Well, it would of course be easy to just store it as JSON, but that way, it could be a bit messy to search for certain stuff in the database (say you wish to check all users from a given city for example).
When it comes to user information, I always find the best way to do this is to store only login vital data and the base info in a users table.
Something like:
id | email | password
And then have different tables for the other data.
Name and such (which a user only has one of (of course one could have multiple names, but I usually only store first and last names)) could be stored in a user_information table, which is in a one to one relation with the user (foreign key for the user_id so that it can be quickly fetched when needed).
When it comes to address and phone number, a user could actually have multiple.
I understand that its possible that your system/app is only supposed to support one address or one phone number and the like, but its always nice to make it "right" from the start, so that its easy to just let the user add multiple of them whenever the need is there.
That way, you would have a few different tables:
users
user_information
addresses
phone_numbers
and so on...
The user_information, addresses and phone_numbers would preferably all have a user_id column which would be used for a foreign key to point at the user who owns it. And if you wish to make it possible to use the same tables for contacts, a contact_id could be added too (and a foreign key to point to the contact).

Multi regional marketplace database design with MySQL

I'm looking for guidance on the database structure for a multi-regional website.
I am setting up a website, similar to craigslist.com, that will allow users to post adds in their city. I am using a MySQL database.
I want to have regions as subfolders linked to subdomains e.g. ca.mysite.com goes to mysite.com/ca.
My question is how do I manage the database(s) when I want to add another city to my website.
If I use a different database for each city, then users wont be able to login to other cities as their login details are stored in the city they registered at in the users table of it's db.
This may not be an issue though, as the content is city specific, like craigslist.
But, should they wish to contact users in other cities, they wont be able to.
Also, there would be duplicate username's and email addresses overall, as users could register in all of the cities using the same email and username.
If I create a central database with for instance, a users table, and a messages table, and then a separate db for each city with all that cities 'posts' then when displaying basic information I will need to consult the city specific db plus the central db that stores user info.
Alternatively I could store everything on one database, and store the logged-in user's location in a cookie, pass that to a session variable, and use that location as part of the database query when displaying search results etc.
However, would this not add an unnecessary overhead to each query?
e.g. every search would have to have ' AND location = $user_location ' added in.
I really have no idea what would be the best method here.
Thanks in advance for any help on this.
It seems that you still do not know clearly the system you want to build. Before starting designing a database for this system, please make sure that you have the full description of the system requirements. Some sample questions that help you clarify are:
What features does your website offer?
What are all the actions that a user using your system can do? With each action, is there any restrictions?
Some other questions relating to the system performance:
- How many users do you expect to use your system?
- How fast and correct each action should be served? Which actions are used frequently?
It makes no sense to design a system without a careful understanding about the system requirements.
So here is the sample database design and how it can support your requirements.
Cities(cityid, cname)
Users(userid, fname, lname, cityid, currcityid)
Messages(mid, senderid, receiverid, content)
Adverts(aid, title, content, userid, cityid)
When a user switches the city, update the currcityid field in its row in the Users table.
When a user posts an ad on a city, insert a new row to the Adverts table. The userid and cityid of the new row are the ids of the corresponding user and city.
When a user sends a message to another user in the system, add a row to the Messages table. The senderid and the receiverid of the new row are the ids of the corresponding users.
Query all ads in a city: SELECT * FROM Adverts WHERE cityid = $cityid
Query all ads of a user: SELECT * FROM Adverts WHERE userid = $userid
Query all ads of a user in a specific city: SELECT * FROM Adverts WHERE cityid = $cityid AND userid = $userid
Hope this helps.

Basic MYSQL/PHP Event Registration (Database Relationships)

I am relatively new to to database relationships, and I would love some advice on setting up my database for a basic registration for sessions.
GOAL:
Post a new session that people can sign up for. Maximum of 8 people per session. Admin side can see those who have signed up.
Here is what I currently have from a front end (the signup box at the bottom is just there temporarily as I work with this):
I have the backend working to create a new training session on POST:
<?php
session_start();
include ('global/db/connection.php');
$session_name = $_POST['session_name'];
$session_description = $_POST['session_description'];
$session_date = $_POST['session_date'];
$result=MYSQL_QUERY("INSERT INTO trainingsessions (id,session_name,session_description,session_date,session_open_slots,session_booked_slots)".
"VALUES ('NULL', '$session_name', '$session_description', '$session_date', '8', '0')");
header("location: admin.php");
?>
I also have been able to query the table and display the results in the table above. What I am trying to figure out is what sort of relationship and tables I need to create between the users and then displaying the appropriate amount of slots that are still open.
Very basic, nothing fancy at the moment. Just trying to get some fundamentals in with not luck thru other searches. Hope this makes sense, and thanks for your help!
You will have a many to many relationship between users and sessions (presumably). In essence each user could be assigned to many sessions, and each session will have multiple users. For that reason, you need an intersecting table that creates a composite key (the primary key is defined by multiple fields). For example, I would make the following tables:
Table: user
Columns: ID (primary key), Username, email
Table: sessions
columns: ID (primary Key), Name, Description, Date
Table: user_sessions
columns: user_id, session_id
Using this structure, users can have multiple sessions and sessions can have multiple users.

Incorporating Open ID with my current login System?

I am currently setting up Open ID authentication in my website and I am having troubles incorporating it with my current Login System and database... I've read the article at Plaxo & it recommends this type of table to store the openid info...
create table user_openids (
openid_url varchar(255) not null,
primary key (openid_url),
user_id int not null,
index (user_id)
);
This is my current Users-info table
Userid(PRIMARY) | username(UNIQUE) | password | Email
Userid is used to reference user-details for comments, ratings etc. (So it goes into the comments table and the ratings table as a User identifier)
I want a system similar to what Stack overflow uses just login using your Open ID and it gives you an unknown(OPENID-provider) display name.... while keeping my current login system intact.
1) How can I add Open ID details of users to my current Users-Info Table without affecting the current login setup?
2) Currently I use User-id(generated unique for every user) to store in the session to maintain Login. What should I do now in case of Open ID?
*My Thoughts(I don't know if I am right or not)
- Add an open-id field to store the unique open id url provided by the open id provider for each user and set it to null for non-open-id-users.
- Make User-id a text field and store a md5 of the open id url.(store this in session to maintain Login).
- I have no idea how can I handle Display-name/Username which is set to unique for each user because I would like to show unknown(OPENID_provider) (for users using open-id) which can be changed from the profile settings...
Any suggestions would be helpful....Thanks
The idea with the table layout you show is to have a 1:many from users:openids.
Thus, no changes to the users table are needed.
When someone logs in with an OpenID, you check if that OpenID is in the openids table. If so, you have the user_id of the user and you are done.
Otherwise create a new user (with no username/password set) and insert an (openid,user_id) pair for them into the openids table.
You template can display whatever nice placeholder (such as their OP, or whatever) where it would normally display username for users whose username is blank.
Hopefully you already disallow logging in with blank passwords, so there should be no security issue there.
What about this?
Add a display_name column to the users table, which doesn't have to be unique.
Make username and password in users optional
When somebody registers with OpenID, create a row in users with empty username/password and display name set to "unkonwn (provider)".
Allow users to set username/password, if they want to switch to password-based login.
Allow users to manage their OpenIDs, so that existing users can switch to OpenID-based login.
This means that users can have username/password, but they don't have to. They also can have one or multiple OpenIDs, but they don't have to. They can use non-unique display name.
Option 1: Only one login type is allowed
Here's my suggestion (UPDATED to prevent the need to edit all business logic related to username):
Create a new column called loginid to allow the storage of OpenIDs and old usernames, Add the UNIQUE INDEX on this column as well.
Populate loginid with existing data from username
DELETE INDEX from username to allow them to be non-unique. When creating a new user from OpenID, set username value to unknown(google) as described.
Keep password for legacy logins, ignore it for OpenID.
Update only the AUTH portion of your code to look for loginid rather than username.
Option 2: Allow multiple logins (also easily extends to linking multiple profiles from various sources)
Create a new table to stand as a master user table and contain all required fields per user (maybe email from your example above).
Create a table to store authentication containing: userid (FK to master record), username (stores the username appropriate to the login scheme), password
There are obviously flaws with both of these options, but it will hopefully get you started in the right direction.

Categories