How to setup relationships in contact Database - php

I am currently embarking on a new venture to learn PHP and MySQL. I have done some simple databases in the past using Access, but this one is to be a web-centric database for tracking a myriad of data including contacts and project information. I will need to link the various tables in various relationships, and I am not sure the best way to do that. Since I am just starting out with PHP/MySQL I am researching online sources for learning as much as possible. If anyone has recommendations on books or websites, I would appreciate it.
In setting up my tables, one major area that I am concerned with is contacts. I will have a variety of contacts that include: employees, clients, vendors, subcontractors, etc.. and a single contact can be multiple types and each type would have various additional fields that pertain to them. My thought was to have one contacts table that links to other tables for the various contact types. I'm not sure which field type or setup of table options are best... Thoughts?
This scenario will likely play out in other areas of the database as well for projects and products.
Any pointers/direction would be appreciated.
WES

Are you familiar with Object Oriented Design.
In a RDBMS, such as MySQL, I would design the database as follows:
Contacts (first name, last names, etc)
Employees
Vendors
Clients
etc
Your tables that extend Contacts would hold their specific data as well as a contact_id column, which creates the relationship.
As an aside, NoSQL solutions solve this problem natively as they don't have a rigid schema. Meaning you could save various data for each record.

I would give a little thought to how you're going to use those extended fields. Certainly create a table for contacts, and you definitely could create a table for each contact type (employees, clients, etc) with a column connecting the record to the contact table (thus employees would have employee_id, contact_id, propertyOne, propertyTwo, etc).
Another option though, which may be convenient if your application is contact centric and you really just want to be able to associate different kinds of information with contacts, would be to have a contact table, a table containing the types of extended information (say "contactTypes" and it would have the information that a vendor type has a billing address for example) and a third table to actually hold all the data (name-value pairs). This is a bit more fluid in that it will let you add new types of contacts or add fields to a type without actually altering your schema. The first option (Jason McCreary's) might scale better if you're going to have many, many records...
Regarding resources - there's so much out there, I can't even begin to narrow it down for you - look at the php manual and just google "php mysql tutorial" - tons of stuff.

A book I would recommend that helped me a lot is Beginning-PHP-MySQL-Novice-Professional
And make sure you watch the following video, but it might be advanced if you do not know the basics. Bbuild-a-login-system-for-a-simple-website/
For database relations as well as an introduction visit Coding HORROR
I hope this helps..

Related

Front-End for MySQL Forms (Windows or OSX)

[Edit: I have awarded the bounty but not the question, as I feel there is still a chance for a better answer.]
I usually code my MySQL data entry interfaces in php.
But for quick projects where I would like to focus on the web side of things (pulling data from the database), I am looking for a form front-end to MySQL. Ideally, this would be an off-the-shelf Win or OSX program that I can hand over to a friend or client so she can input data into forms.
An Example
The lines above summarize the question, but here is a typical situation to showcase why "just give them phpMyAdmin" or some other web interface to MySQL generally wont work.
We have two main tables: images and albums. The third is an associative table that associates images with albums.
Images: id (PK), filename
Albums: id (PK), album
Album_Image: id (PK), imageid, albumid (these are foreign keys: the two id PKs from the Images and Albums tables)
For big projects, I don't mind coding a nice "back-end" interface (CRUD) that lets me edit data in a very comfortable, customized way.
For small projects, for instance an image gallery for a friend, I would like to be able to only program the "front-end": web interfaces that pull data from the database.
For the back-end, ideally, I would like to give my friend an off-the-shelf solution so she can enter images, albums, and associations between images and albums.
In the old days (I am thinking of DBaseIII), it was really easy to give interfaces to do that entry side of things.
Here is a crude approach I have tried. I have set up a view of the associative table joined to the parent tables, so it shows albumid, imageid (the PKs) and album, filename (associated fields in the parents) using this query:
SELECT albumid, imageid, album, filename FROM album_image axi
JOIN albums a ON a.`id` = axi.`albumid`
JOIN images i ON i.`id` = axi.`imageid`
The idea with this crude approach is that my friend would enter the parent PKs (albumid and imageid) in the associative table through the view, and that after hitting Insert, the full parent fields (filename and album) would be visible in the View for visual feedback. I have tried this view in three GUI tools: SQLyog (Win), HeidiSQL (Win) and Sequel Pro (OSX).
In Heidi and Sequel Pro, I have not found a way to edit the view.
In SQLyog, I can edit the PK fields (albumid and imageid) in the view, and the parent fields (album and filename) show properly when I hit "refresh". That's great. It works because even though the view shows three tables, we are only editing from one table. But I cannot delete a row as SQLyog doesn't know from which of the three tables we are trying to delete. On the other hand, in SQLyog, I able both able to insert and delete in a Query tab that contains the same query that creates the view, because in this kind of tab SQLyog allows me select the table being edited. So that works, but this workflow might start to be a little complex for my friend: she would have to open SQLyog, connect, open a saved query, select the right table to edit within the query, and make all the other right moves.
Wondering if any one knows an existing tool that is really good at making forms for MySQL---ideally a Windows or OSX binary. I will consider a web solution, but I am not interested in a framework---the key is speed of deployment, and if we went the framework route I would be better off making the interface with my own CRUD libraries. Again, I can code it, but my goal with these kinds of "quickie projects" is to focus my workload on the front end (web interface to the database), leaving the back end to an off-the-shelf tool.
Thanks heaps in advance for any insights. :)
Edit: I see that no one has mentioned Navicat or MySQL Workbench. I haven't tried either, wondering if someone knows off the top of their head whether they would do the trick.
I think what you're looking for is a form front-end for MySQL.
Since it sounds like you are more interested in binaries than web apps, have you looked into Microsoft Access? It can talk to MySQL and could be just what you need.
Open Office Base may not have quite the features you're looking for.
You already have the solution, your attempt at making things simpler is creating the complication.
There is no benefit to your friend in adding album images in a view if that view that only shows the filename and album title after they have entered the IDs and clicked Insert.
Before adding an image, your friend needs to know the album ID and the image ID. This information may not be in the view. She will therefore look at the album table and look at the image table to find this information, cross-referencing the filename with her own list of uploaded images.
Then, having written these two numbers down, she can insert a row directly into the album_image.
For visual feedback, she can check the frontend website.
It is true that a view showing the album name and filename would make deleting entries easier, but I would assume that images and albums are added much more frequently than they are deleted.
The ability to edit an associative table in a view that shows linked information, therefore, should not greatly affect your choice of tool. I could suggest tools, and phpMyAdmin is a logical choice, particularly if it is desirable to teach your friend computer skills that are widely applicable. It appears you have already identified some executable tools.
I imagine that you could add some additional hidden frontend views that could make your friend's workflow easier, such as a list of images and IDs that aren't in albums, a list of album IDs, or a view that shows the IDs. I do recommend you consider extending the frontend with a simple login and Edit options using your CRUD library, rather than devising a separate backend GUI.
I appreciate this is not an answer to the exact question, but it does resolve your problem.
I'm not sure if this will be helpful or not. I was hoping to find a UI with some eye candy/styling, but while searching I stumbled upon this:
https://blogs.oracle.com/MySqlOnWindows/entry/introducing_mysql_for_excel
As part of the new product initiatives of the MySQL on Windows group we released a tool that makes the task of getting data in and out of a MySQL Database very friendly and intuitive, and we paired it with one of the preferred applications for data analysis and manipulation in Windows platforms, MS Excel.
Like I said, not sure if it will help. I'm in a similar situation - low-tech, low budget client. The difference is my weakness in MySQL, but for me I just need a single table, so I think this will work.
There is no tool that will allow you delete such values from such a view, not for mysql, since For a multiple-table updatable view ... DELETE is not supported, see Updatable and Insertable Views
I guess you are looking for the equivelent of the Python based Django admin system which practically builds itself from analysis of the data structure.
Frameworks like Symfony, Cake and Yii have some of this built in, however I'm guessing that your database architecture may not be compatable as these types of systems normally require you to stick to strict naming conventions, but it's certainly worth taking a look.
Playful,
I already posted one answer, but this one is different enough to merit a seperate response, IMO.
Since you are looking for a simple, client-friendly solution, may I suggest Adminer?
http://www.adminer.org/en/?
Specifically, I used the Wordpress plugin here on a site recently:
http://wordpress.org/extend/plugins/adminer/
It provides pretty much full phpMyAdmin funcitonality. Very easy for the client, and if they want to, they can export the database as .csv and edit in excel, then re-upload. Just about everyone is familiar with editing in Excel, and they can make backups regularly.
Hope this helps!
J
You can very quickly and easily make a front-end for this type of use with Xataface. I find it very quick and useful. I would be happy to help you get going with it.
www.xataface.com

social network - User profile design schema question

I am creating user profiles on my site and lost on how to design this: There are many fields, some are 1:1 like city of residence, birthday, etc. But there are over 50 fields which are 1:many (or many to many?) like favorite movies, sport teams, dating preference, screen names, phone numbers, email addresses etc. It gets more complex when we have previous companies worked at, previous schools, etc. A person can belong to many companies and there are many fields in this group like Date worked at, department, company name, industry name, etc.
So the question is how to store all this? If we normalize all these profile fields there will be many many tables to join. As far as i read, for social networks people recommend a denormalized approach. But eitherways, I am storing all user details and profile details in the main user table, so each row is a unique user. If i have to store all these multiple preference, esp like favorite movies can go in the hundreds and past companies itself have a whole group of fields, so there will be lots of duplicates in the user table.
What approach do social networks take for this?
Social network data storage questions are really no different than the data storage questions in general... normalized and related data is the best way to 'store' this data efficiently. The RDBMS is made to handle these relationships - the PK-FK relationships and JOINS are the MAIN point of Relational DBs... so even though YOU 'see" join join join etc, the DB is (should be) efficient in handling these joins.
From a USAGE standpoint of getting to the pertinent data - make sure your indexes are accurate and optimized - and make use of VIEWS to 'flatten' the data you need for display purposes...
So whatever application server you are using to get the data will call the VIEW - that will 'appear' to you, the developer, as a 'flatter' representation of the data, making UI and APP serer interaction cleaner and more efficient (both in resources, and in coding),
as a general guideline - flattening of data is generally considered 'acceptable' in a data warehousing environment... of course I don't what to open up the monstrous debate of "just how normalized, is 'normalized'" (first - sixth form of normalization...)
I guess you could think of a SN as more of an OLAP, than the OLTP. In which case 'some' de-normalized data storage is common - and acceptable - really, YOU get to decide just how de-normalized you want things... For instance - in your examples, of employment history and movies, sports. I'd think that a simple 1:many allowing duplicate entries on such items would be fine, and probably easier to maintain...
Hope that was helpful,
You have to stick with the normalization strategy of creating your schema.The query might be a pain which you should handle with extreme caution especially when dealing with joins.If you are a dot developer, i guess LINQ will handle d pain for you.I believe your RDMS is smart enough to handle your queries with great performance. One thing to take note is your query structure.Write performance-based queries.As i said, LINQ should do this best....cheers

Assigning a user to multiple projects in my PHP application, best approach?

I am currently building a web application for my work and you can add tasks, projects and clients. The dilemma I've encountered is that a client can be assigned to multiple projects at once.
The application is being built upon the latest version of Codeigniter 2.0 (if that helps). I am usually pretty good at working out problems like this, but I can't get my head around this one.
One solution I came up with is to store a list of project ID's for the client in a table field called 'belongs_to' and separate them by comma. Sure this method would work, but it just seems a little messy and I am sure that there is another way, my mind just can't come up with the solution.
Your help is gratefully appreciated.
Why not just have 3 tables:
Table projects: id, name, etc etc
Table clients: id, name, etc etc
Table clients2projects: id, id_project, id_client
In this way the third table maps projects and clients in a many to many relationship

Multi-company web application database security

My question is very similar to this question but a bit more specific.
My application has multiple companies and multiple users per company. It makes the most sense to me (at this point) for each company to have a "private" set of tables. This makes security extremely simple as I don't have to worry about JOIN-ing up my structure tree to be sure I only get data for the specific company. I can also extend the mysqli database extension and have it put a prefix on the table names in the query so that I never have to worry about security while writing my queries.
One other major advantage that I can see is that if one of the companies needs a customization, I can modify their specific tables and not have to take into account everyone else. The way that my app is designed it is extremely modular and implementing custom code is very simple.
There are some disadvantages that I can see but so far it seems that the above advantages would out-weigh them. The above proposed system does sort of grate on my (possibly) hyper-normalized database schema preferences up to this point. Another obvious disadvantage is implementing schema alterations but I can script them and be safe enough. One point that I'm not sure about is performance. If I have MySQL working with so many tables, will I make bottlenecks for myself?
I look forward to your thoughts!
Your proposal sounds reasonable to me. I would suggest that instead of prefixing your tables with the company name, you store the tables for each company in a separate schema. That way you can have tables with the same name, reducing your problems in the code, and have each set of tables protected by a different username and password in a convenient manner. Backups and replication would then all be distinguishable at need.
Lookup tables could be stored in yet another schema to which all users have access.

Understanding large mysql data relations

I am trying to teach myself how to use SQL, namely mysql.
What I am trying to understand is how to deal with many different types of data with in the same table. Say I am building a web application, and I have many different content types (blog item, comment item, files, pages, forms) that I need to store different data fields for each. Would I create a new table for each different content type since each content type has its own unique field requirements, or is there a better way to do this? It seems a little much to create a new table for content each type. If I had 30 types of content in my web app, that would be 30 tables just for the types, which seems a little much. And, if I had a new content type, I would have to create a new table that contained all the required fields I would need for that type.
Is there a better way to do something like this, when I have many different types of content that each requires different fields of data that needs to go into the database? Can I somehow check to see what type the content is, then select another table that holds all the different field types?
A little confused about what to do.
Just to give an example:
Stack Overflow itself uses the same database table (called Posts) for questions and answers. Even though these two types of data are not identical, the site creators considered them similar enough to put them into one table. There's a PostTypeId field that says whether this post is a question or an answer. On answers, the Title field would be NULL, on questions, other columns might be ignored.
Comments, on the other hand, are in a different table. Of course you could theoretically put them into the same Posts table and have a PostTypeId for comments. But the overhead this would create (because of the lightweightness of comments) justifies creating a new table.
I know this isn't really an answer, and other developers might even have decided to put questions and answers into different tables; but it gives some perspective. Long story short: It depends :)
Sketch interactions
First try not to think about database design, but how entities should interact between themselves. Think of it as each entity has its own Class, which represents required data.
It's always a good start to take pencil and paper and sketch your interactions between these entities, on what interactions (or relations) are you trying to accomplish. Learning the Database design process
Extendability and reuse
For example you want to have a User, which can post BlogPosts each BlogPost can have a set of Tags and relevant set of Comments. Attachments can be injected into BlogPost and also into Comment.
Reusability and extendability is the key. When sketching your interactions try to isolate dependencies. Think of it in OO manner. Let's explore the Attachment a little more. You can create an Attachment table and then extend Attachement by creating BlogPostAttachment and CommentAttachment where you can easily create relations between these dependable entities. This creates an easily extendable content type which you can further reuse in eg. UserDetailsAttachment
ORM's to rescue
By studying example code usage of Object relational mappers like Doctrine or Propel you can grasp some ideas for table extendabity. Practical examples are always the best one.
Related SO questions, which you may be interested in
Good Resources for Relational Database Design
Good PHP ORM Library?
How should a programmer learn great database design?
I know, it's a long way to go, but considering factors of creating large scale DB applications with many relations and entity types it best to use help of ORM in the long run
You needn't be afraid of using many many tables - the database will happily deal with lots of them without complaining. If you let each content type have its own table, you get certain advantages:
Simplicity: Each table can be fairly simple, and the constraints are straightforward. For example if ContentType1 has a field with a relation to another table, you can make that a foreign key in the database design and the RDBMS will take care of data integrity for you.
Indexing efficiency: if ContentType2 needs to be indexed by date but ContentType3 needs to be indexed by name (to take a simple example), having them in two separate tables means each index is there for exactly the data it needs and nothing else. Combining them in one table means you need both indexes covering the combined dataset, which is messier and uses up more disk space.
If you need to output a list combining two content types, a UNION of the two tables is both easy; and if you need to do that often with large amounts of data, an indexed view can make it cheap.
On the other hand, if you have two content types which are very similar (as in the StackOverflow case above for example), you can get some advantages from combining them into one table:
Simplicity: You only need to code the table once - if done right (i.e. the two content types are really very similar), this can make your codebase smaller and simpler.
Extensibility: if a third content type crops up which is again similar to the first two, and similar in the same way that the first two match each other, the table can straightforwardly be extended to store all three content types.
Indexing for performance. If the most common way of getting at the data is to combine the two content types and order them by date (say), a field which is common to both content types, then it can be inefficient to have two separate tables which must repeatedly be UNIONed and then sorted. Combining the two content types in one table lets you put a single index on the date field, allowing faster querying (though remember you can get a similar benefit from indexed views).
If you normalize rigorously, you will have a database where every entity type has its own table in the database. However, denormalization in various ways (such as combining two entity types in one table) can have benefits which might (depending on the size and shape of your data) outweight the costs. I'd advise a strategy of keeping all content types separate at least at first, and consider combining them as a tactical denormalization if it turns out to be necessary.
You need to read a book about building websites with PHP and MySQL. It's a good attitude to google first because some programmers think it is a lazy question. I suggest reading "Learning PHP MySQL and JavaScript".
Anyway, before you start coding your site, you need to plan what kinda information you will store, then you design your database. Say a register form will contain A First_Name, Second_Name, DateOfBirth, Country, Gender and Email. You create a table named as say "USER_INFO" and you assign a datatype matching the data you would like to store, a Number, text, Date, and So on, then via PHP you connect to MySQL and store or retrieve the data you want. You really need to read a book or a tutorial so you get a full answer, AND GOOGLE :P

Categories