Trải qua 25 bài php căn bản thì chúng ta mới chỉ tìm hiểu râu ria bên ngoài các kiến thức về kỹ thuật lập trình nên có lẽ các bạn cảm thấy chưa HƯNG PHẤN ,vì vậy để các bạn không bị chán thì trong bài này chúng ta sẽ tìm hiểu cách kết nối CSDL MYSQL với php và một số hàm xử lý database nhé.

Nội dung chính

  • 1. Tạo Database
  • 2. Kết nối database với php
  • 3. Câu truy vấn lấy danh sách record
  • 4. Câu truy vấn delete
  • 5. Câu truy vấn update
  • 6. Lời kết



1. Tạo Database

Trước tiên chúng ta tạo một database để test đã nhé, các bạn vào phpmyadmin và tạo một cơ sở dữ liệu tên là demo và tạo một table tên là customer bằng cách chạy câu truy vấn sau:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
CREATE TABLE IF NOT EXISTS `customer` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` VARCHAR(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address` VARCHAR(500) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
INSERT INTO `customer` (`id`, `name`, `phone`, `address`) VALUES
(1, 'Nguyen Van A', '0970 306 603', NULL),
(2, 'Nguyen Van B', '0970 306 603', NULL),
(3, 'Nguyen Van C', '0970 306 603', NULL),
(4, 'Nguyen Van D', '0970 306 603', NULL);

 

Chúng ta sẽ thao tác với dữ liệu này.

2. Kết nối database với php

Để kết nối vào database ta sẽ dùng hàm mysqli_connect với cấu trúc như sau:

 

1
mysqli_connect($host, $user, $password, $database, $port, $socket).

 

Trong đó:

  • $host: là địa chỉ host của bạn, thông thường là localhost luôn
  • $user: là tên đăng nhập vào database
  • $password: là mật khẩu kết nối vào database
  • $database: Tên database bạn chọn để xử lý
  • $port: Cổng kêt nối
  • $socket: Phương thức socket kết nối

Ví dụ:

 

1
$conn = mysqli_connect('localhost', 'root', 'vertrigo', 'demo') or die ('Không thể kết nối tới database');

 

Tất cả những tham số đó thì ta chỉ quan tâm đến 4 tham số đầu tiên, 2 tham số còn lại bạn khỏi truyền vào nhé. Còn đoạn code or die ('Không thể kết nối tới database') dùng cho trường hợp không thể kết nối tới CSDL thì sẽ in ra màn hình dòng thông báo đó.

3. Câu truy vấn lấy danh sách record

Bạn tạo file demo.php với nội dung như sau:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Kết nối CSDL và lưu vào biến kết nối
// Các tham số gồm:
// - localhost: là tên server, thường mặc định là localhost luôn
// - root: là tên đăng nhập vào database
// - vertrigo: là mật khẩu đăng nhập vào database
// - demo: Là database sẽ xử lý
$conn = mysqli_connect('localhost', 'root', 'vertrigo', 'demo') or die ('Không thể kết nối tới database');
// Câu truy vấn
$sql = 'SELECT * FROM CUSTOMER';
// Thực hiện câu truy vấn, hàm này truyền hai tham số vào là biến kết nối và câu truy vấn
$result = mysqli_query($conn, $sql);
// Nếu thực thi không được thì thông báo truy vấn bị sai
if (!$result){
    die ('Câu truy vấn bị sai');
}
// Lặp qua kết quả và in ra ngoài màn hình
// Vì các field trong database là id, name, phone, address nên
// khi vardum mang sẽ có cấu trúc tương tự
while ($row = mysqli_fetch_assoc($result)){
    var_dump($row);
}
// Xóa kết quả khỏi bộ nhớ
mysqli_free_result($result);
// Sau khi thực thi xong thì ngắt kết nối database
mysqli_close($conn);

 



Để thực thi câu truy vấn bất kỳ thì ta dùng hàm mysqli_query()nếu câu truy vấn trả về danh sách thì ta sẽ dùng vòng lặp while để hiển thị nó ra. Chi tiết mình đã mô tả trong phần comment rồi nhé.

4. Câu truy vấn delete

Tương tự như phần 3, bạn sẽ viết một câu truy vấn delete và sau đó dùng hàm mysqli_query() để thực hiện.

Ví dụ:

 

1
2
3
4
5
6
7
8
9
10
11
12
$conn = mysqli_connect('localhost', 'root', 'vertrigo', 'demo') or die ('Không thể kết nối tới database');
// Câu truy vấn
$sql = 'DELETE FROM customer WHERE id = 1';
// DELETE
if (mysqli_query($conn, $sql)){
    echo 'Xóa thành công';
}
// Ngắt kết nối
mysqli_close($conn);

 

5. Câu truy vấn update

Ta sẽ viết một câu truy vấn update và thực thi tương tự như phần 3,4.

Ví dụ:

 




1
2
3
4
5
6
7
8
9
10
11
12
$conn = mysqli_connect('localhost', 'root', 'vertrigo', 'demo') or die ('Không thể kết nối tới database');
// Câu truy vấn
$sql = "UPDATE customer SET name = 'TEN MOI' where id = 2";
// DELETE
if (mysqli_query($conn, $sql)){
    echo 'Cập nhật thành công';
}
// Ngắt kết nối
mysqli_close($conn);

 

Note: Vì các bạn đang học hàm kết nối nên ở mỗi thao tác bạn vào database xem có thay đổi không nhé, ở những bài tiếp theo mình sẽ hướng dẫn viết HTML cụ thể hơn.

6. Lời kết

Trong bài này chỉ mang tính chất giới thiệu cách sử dụng một số hàm kết nối bằng cách dùng MYSQLI, ở những bài tiếp theo chúng ta sẽ tìm hiểu cụ thể và rõ ràng hơn. Bài tiếp theo chúng ta sẽ viết chức năng đăng ký thành viên với PHP. Chúc các bạn học tốt.

488 BÌNH LUẬN

  1. I think other website proprietors should take this site as an model, very clean and wonderful user friendly style and design, as well as the content. You are an expert in this topic!

  2. Your posts customarily consist of a correct amount of truly up to date information. Everyplace accomplish you extend up with this? Emphatically declaring you are fantastically creative. Thanks again

  3. Wonderful blog! I found it while browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Thank you

  4. I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You are amazing! Thanks!

  5. IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžm a lengthy time watcher and I just considered IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžd drop by and say hello there there for the very initially time.

  6. This unique blog is really awesome as well as factual. I have discovered a lot of useful tips out of this amazing blog. I ad love to come back over and over again. Cheers!

  7. You have mentioned very interesting points ! ps decent website. What a grand thing, to be loved What a grander thing still, to love by Victor Hugo.

  8. La prevalencia de esta enfermedad se estima en torno al 1– 10% en menores de 40 años, 2– 9% entre los 40 y los 50 años, un 20– 40% entre 60 y 70 años y 50– 100% en mayores de 70 años. La entrega gratis por toda España. ¿Qué son los problemas para mantener la erección? Tadalafil bajo el nombre de Cialis se usa en el tratamiento de la disfunción eréctil (impotencia) y síntomas de hiperplasia prostática benigna (próstata agrandada).

  9. Hey this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with
    HTML. I’m starting a blog soon but have no coding know-how so I wanted to get
    advice from someone with experience. Any help would be
    enormously appreciated!

  10. Los sobre loa problemas de la la disfunción eréctil no se ha hablado nunca libremente, porque la gente piensa que es algo que debe permanecer en secreto y de esto han sufrido muchos de los hombres que han tenido temor de discutir sus problemas sexuales con un especialista, es humillante para el hombre y lo pone en una situación sin salida.

  11. Heya i am for the first time here. I found this board and I find It truly useful & it helped me out a lot.

    I hope to give something back and help others like you aided me.

  12. Greetings I am so glad I found your webpage, I really found you by mistake, while I was browsing on Askjeeve for something else, Anyways I am here now and would
    just like to say thanks for a marvelous post
    and a all round interesting blog (I also love the theme/design), I don’t have time to read it all at the moment but I have saved it and also added in your
    RSS feeds, so when I have time I will be back to read much more, Please do keep up the
    fantastic work.

  13. Do you mind if I quote a couple of your articles
    as long as I provide credit and sources back to your blog?

    My blog site is in the very same niche as yours and my visitors would really benefit
    from some of the information you provide here. Please let me know if this ok with you.
    Thanks a lot!

  14. You have made some really good points there. I looked on the net for additional information about the issue and found most individuals will go along with your views on this site.

  15. This blog is obviously cool additionally informative. I have chosen a bunch of useful stuff out of this blog. I ad love to return every once in a while. Thanks a lot!

  16. This is really interesting, You are a very skilled blogger. I ave joined your feed and look forward to seeking more of your fantastic post. Also, I ave shared your web site in my social networks!

  17. It as really a great and useful piece of information. I am satisfied that you just shared this useful tidbit with us. Please stay us up to date like this. Thank you for sharing.

  18. Sweet blog! I found it while browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Appreciate it

  19. Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, let alone the content!

  20. Wow! This could be one particular of the most beneficial blogs We ave ever arrive across on this subject. Actually Excellent. I am also an expert in this topic so I can understand your effort.

  21. You can definitely see your expertise in the work you write. The arena hopes for more passionate writers like you who aren at afraid to say how they believe. At all times follow your heart.

  22. Wow! This could be one particular of the most helpful blogs We have ever arrive across on this subject. Actually Fantastic. I am also an expert in this topic therefore I can understand your effort.

  23. Spot on with this write-up, I absolutely feel this amazing site needs far more attention. I all probably be returning to read through more, thanks for the information!

  24. I was recommended this blog by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are incredible! Thanks!

  25. You acquired a really useful blog site I have been here reading for about an hour. I am a newbie and your accomplishment is extremely considerably an inspiration for me.

  26. I think other site proprietors should take this site as an model, very clean and excellent user genial style and design, let alone the content. You are an expert in this topic!

  27. Wow! This could be one particular of the most beneficial blogs We have ever arrive across on this subject. Basically Great. I am also an expert in this topic therefore I can understand your hard work.

  28. I was very happy to discover this website. I want to to
    thank you for your time for this wonderful read!! I definitely loved every part of it and
    i also have you book marked to see new information on your web site.

  29. Thanks a bunch for sharing this with all people you really realize what you’re talking approximately!
    Bookmarked. Please also seek advice from my web site =).
    We may have a link exchange contract among us

  30. You are so cool! I don’t think I’ve read through anything like this before. So great to discover somebody with original thoughts on this subject matter. Really.. thank you for starting this up. This website is something that’s needed on the web, someone with a bit of originality!|

  31. Wonderful post however , I was wanting to know if you could write a litte more on this subject? I ad be very grateful if you could elaborate a little bit further. Appreciate it!

  32. I was suggested this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You are incredible! Thanks!

  33. Whats up. Very cool blog!! Man.. Excellent.. Amazing.. I all bookmark your website and take the feeds alsoI am glad to find numerous useful information here in the post. Thank you for sharing

  34. Wow, awesome blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your site is fantastic, let alone the content!

  35. Pretty nice post. I just stumbled upon your blog and wished to say that I ave truly enjoyed browsing your blog posts. In any case I all be subscribing to your feed and I hope you write again soon!

  36. Full body massage will be a useful technology in many ways. It is good for relieving stress of friends and family members, and it can also help relieve pain or pain of people around them.

  37. scoliosisI like the helpful info you provide in your articles.I will bookmark your blog and check again here regularly.I am quite sure I will learn plenty of new stuff right here!Best of luck for the next! scoliosis

  38. Thanks for your marvelous posting! I truly enjoyed readingit, you are a great author.I will ensure that I bookmark your blogand will often come back later in life. I want to encourage one to continue your greatwork, have a nice evening!

  39. Somebody essentially lend a hand to make seriously articles I would state. That is the very first time I frequented your website page and to this point? I surprised with the analysis you made to make this actual post extraordinary. Excellent task!|

  40. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a commentis added I get four emails with the same comment.Is there any way you can remove people from that service?Many thanks!

  41. What’s Taking place i am new to this, I stumbled upon this I’ve found It absolutely useful and it has aided me out loads. I am hoping to give a contribution & help different users like its helped me. Great job.

  42. My brother suggested I may like this blog. He used to be entirely right. This submit truly made my day. You cann’t imagine simply how a lot time I had spent for this information! Thanks!

  43. We stumbled over here by a different web page and thought I might check things out. I like what I see so i am just following you. Look forward to going over your web page for a second time.

  44. I will immediately seize your rss as I can not find your e-mail subscription hyperlink or e-newsletter service. Do you have any? Please permit me realize in order that I may just subscribe. Thanks.

  45. Having read this I thought it was extremely informative. I appreciate you spending some time and energy to put this content together. I once again find myself spending way too much time both reading and leaving comments. But so what, it was still worthwhile!|

  46. I’а†ve learn a few just right stuff here. Certainly price bookmarking for revisiting. I surprise how so much effort you place to make this type of magnificent informative site.

  47. Simply wish to say your article is as surprising. The clearness on your post is simply excellent and i could think you are knowledgeable on this subject. Well along with your permission allow me to grab your RSS feed to stay updated with coming near near post. Thank you a million and please carry on the rewarding work.|

  48. I’m really enjoying the design and layout of your blog.It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did youhire out a developer to create your theme? Excellent work!

  49. I don’t even understand how I stopped up right here, however I believed this put up was once great. I do not realize who you might be however definitely you’re going to a famous blogger in the event you aren’t already 😉 Cheers!

  50. Hi my friend! I wish to say that this post is awesome, nice written and include approximatelyall vital infos. I would like to see more posts likethis .

THOÁT KHỎI BÌNH LUẬN

Please enter your comment!
Please enter your name here