An undergraduate degree is the first degree you do at university. Usually it is a 3 year course but it may be longer for some degrees (such as engineering or medicine). You may be awarded a title "BSc" which means Bachelor of Science. Other degrees may award different things depending on the field.
A masters degree is a postgraduate degree, done after an undergraduate degree. It usually lasts 1-2 years and awards people with titles such as "MSc" which means "Master of Science" in a certain topic. Other degrees may award different things depending on the field. I believe the majority of masters degrees include some research based content, but I am not sure if all of them do. Some exclusively focus on research and you are awarded a title "MRes" meaning "Master of Research".
Some undergraduate degrees are actually "integrated masters" and therefore include a masters degree directly after you do the bachelor degree program. For example, engineering programmes are often like this. They would offer 4 year courses (3+1) and award a "MEng" title which means "Master of Engineering".
For all cases above, usually the following holds in the UK, where the percentage corresponds to your overall degree mark (calculated over the whole year(s)):
70%+ > "First-Class Honours"> 1st.
60-69% > "Upper Second-Class Honours" > 2:1
50%-59% > "Lower Second-Class" > 2:2
40%-49% > "Third-Class Honours" > 3rd
Note that many graduate employers in the UK now expect a 2:2 degree and many will also want a minimum of a 2:1 degree.
A PhD is a research based degree. It is a postgraduate degree and is specifically called a "doctorate degree" to distinguish it from a masters postgraduate degree. You do it after you do your first degree (usually a bachelors) and often also after your second degree (a masters). You can however go directly from a bachelors to a PhD degree. In the UK you carry out research for three years and then write a long report called a thesis which describes and discusses your findings.
The research can be a laboratory experiment(s), computer simulation(s), social science experiment (surveys etc) or some combination of all three. You defend your thesis (your research) to a panel in what is called a "viva". This is basically similar to an interview, where a panel of people in your field will ask you questions about your work. If you pass, then you are awarded the Doctor of Philosophy degree and this also allows you to use the "Dr" title.
A medical doctor does a medicine degree in university, which is an undergraduate degree. This can last 5-6 years. I don't have much knowledge in when they can use the title "Dr's". But as far as I understand it, when medical students, dentists and vets are sufficiently trained, they are given these titles.
Note that it is possible and common for a person who becomes a medical doctor to also do a PhD degree, although the latter is not a requirement for them to awarded the "Dr" title.