Sau khi tạo database bằng PHP thì chúng ta sẽ tiếp tục sư dụng PHP để tạo các table. Để tạo table thì ta sử dụng câu lệnh SQL Create Table.

Nội dung chính

  • 1. Tạo table bằng code PHP
  • Sử dụng MySQLi Object-oriented:
  • Sử dụng MySQLi Procedural:
  • Sử dụng PDO:
  • 2. Kết hợp tạo table với tạo Database
  • 3. Lời kết
  1. Tạo table bằng code PHP

Tương tự như các bài trước mình sẽ đưa ra ví dụ cho cả ba trường hợp.

Giả sử mình cần tạo một table bằng lệnh SQL sau:

1

2

3

4

5

6

CREATE TABLE News (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(30) NOT NULL,

content TEXT,

add_date TIMESTAMP

)

Hình ảnh table:

Mình sẽ không giải thích ý nghĩa của từng đoạn query SQL nữa vì mình có một series học MySQL căn bản rồi.

Bây giờ ta sẽ tìm hiểu các cách tạo table bằng code PHP.

Sử dụng MySQLi Object-oriented:

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

// Kết nối

$conn = new mysqli(‘localhost’, ‘root’, ‘vertrigo’, ‘FreetutsDemo’);

 

// Kiểm tra kết nối

if ($conn->connect_error) {

die(“Kết nối không thành công: ” . $conn->connect_error);

}

 

// sql to create table

$sql = “CREATE TABLE News (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(30) NOT NULL,

content TEXT,

add_date TIMESTAMP

)”;

 

// Thực thi câu truy vấn

if ($conn->query($sql) === TRUE) {

echo “Tạo table thành công”;

} else {

echo “Tạo table thất bại: ” . $conn->error;

}

 

// Ngắt kết nối

$conn->close();

Sử dụng MySQLi Procedural:

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

// Kết nối

$conn = mysqli_connect(‘localhost’, ‘root’, ‘vertrigo’, ‘FreetutsDemo’);

 

// Kiểm tra kết nối

if (!$conn) {

die(“Kết nối không thành công: ” . mysqli_connect_error());

}

 

// Câu lệnh SQL

$sql = “CREATE TABLE News (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(30) NOT NULL,

content TEXT,

add_date TIMESTAMP

)”;

 

// Thực thi câu truy vấn

if (mysqli_query($conn, $sql)) {

echo “Tạo table thành công”;

} else {

echo “Tạo table thất bại: ” . mysqli_error($conn);

}

 

// Ngắt kết nối

mysqli_close($conn);

Sử dụng PDO:

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

try {

// Kết nối

$conn = new PDO(“mysql:host=localhost;dbname=FreetutsDemo”, ‘root’, ‘vertrigo’);

 

// Thiết lập chế độ exception

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 

// Câu lệnh SQL

$sql = “CREATE TABLE News (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(30) NOT NULL,

content TEXT,

add_date TIMESTAMP

)”;

 

// Thực thi câu truy vấn

$conn->exec($sql);

 

echo “Tạo table thành công”;

}

catch (PDOException $e) {

echo $e->getMessage();

}

 

// Ngắt kết nối

$conn = null;

  1. Kết hợp tạo table với tạo Database

Bây giờ mình sẽ đưa ra một ví dụ về cách kết hợp tạo databaes và tạo table cùng trên một file PHP. Để các bạn dễ hiểu thì mình sẽ lấy thư viện MySQLi hướng thủ tục để làm ví dụ nhé.

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

32

33

34

35

36

37

38

39

40

41

42

// BƯỚC 1: TẠO DATABASE

// Tạo kết nối

$conn = mysqli_connect(‘localhost’, ‘root’, ‘vertrigo’);

 

// Nếu kết nối thất bại

if (!$conn) {

die(“Kết nối thất bại: ” . mysqli_connect_error());

}

 

// Lệnh tạo database

$sql = “CREATE DATABASE FreettusDemo”;

 

// Thực thi câu truy vấn

if (mysqli_query($conn, $sql))

{

echo ‘Tạo database thành công!’;

 

// BƯƠC 2: TẠO TABLE

// Chọn database

mysqli_select_db($conn, ‘FreettusDemo’);

 

// Câu lệnh SQL

$sql = “CREATE TABLE News (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(30) NOT NULL,

content TEXT,

add_date TIMESTAMP

)”;

 

// Thực thi câu truy vấn

if (mysqli_query($conn, $sql)) {

echo “Tạo table thành công”;

} else {

echo “Tạo table thất bại: ” . mysqli_error($conn);

}

 

} else {

echo “Tạo database thất bại: ” . mysqli_error($conn);

}

 

// Tạo xong thì ngắt kết nối

mysqli_close($conn);

Bạn đọc phần coment là sẽ hiểu quy trình hoạt động.

  1. Lời kết

Như vậy là bạn đã chạy được hai câu truy vấn tạo database và tạo table bằng code PHP rồi đấy. Thực tế thì rất ít khi chúng ta đụng đến hai vấn đề này trừ khi các bạn xây dựng một CMS hoặc một tools nào đó. bài tiếp theo chúng ta sẽ tìm hiểu cách insert database bằng code PHP.

321 BÌNH LUẬN

  1. I’ve been browsing on-line more than three hours lately, but I by no means discovered any interesting article like yours.
    It’s lovely price enough for me. In my opinion, if all web owners and
    bloggers made just right content as you probably did, the internet will probably be much more
    helpful than ever before.

  2. Hi there! This is my 1st comment here so I just wanted to give a
    quick shout out and say I really enjoy reading through your posts.

    Can you suggest any other blogs/websites/forums that deal
    with the same topics? Thank you so much!

  3. Im no expert, but I think you just crafted a very good point point. You definitely understand what youre talking about, and I can truly get behind that. Thanks for being so upfront and so truthful.

  4. Ita??a?аАа’аАТ‚аЂ s really a nice and useful piece of information. Ia??a?аАа’аАТ‚аЂ m satisfied that you shared this helpful info with us. Please stay us informed like this. Thank you for sharing.

  5. You ave made some decent points there. I checked on the internet for additional information about the issue and found most people will go along with your views on this site.

  6. Thanks a whole lot for sharing this with all of us you really know what you are speaking about! Bookmarked. Kindly also check out my web-site =). We could possess a link exchange contract amongst us!

  7. You can certainly see your skills within the work you write.

    The sector hopes for more passionate writers such as you who aren’t afraid to mention how they believe.
    All the time go after your heart.

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

  9. You have noted very interesting details ! ps nice web site. We make ourselves a ladder out of our vices if we trample the vices themselves underfoot. by Saint Augustine.

  10. We are a group of volunteers and opening a new scheme in our community.
    Your site provided us with valuable info to work on. You’ve done an impressive
    job and our whole community will be thankful to you.

  11. Very nice article and straight to the point. I am not sure if this is actually the best place to ask but do you people have any thoughts on where to hire some professional writers? Thanks in advance

  12. one other and this design of partnership is a complete great deal extra genuine wanting and passionate. You might effortlessly come about across a right match for your self by way of video

  13. Normally I do not learn article on blogs, however I would like to say that this write-up very compelled me to try and do so! Your writing taste has been amazed me. Thank you, quite great article.

  14. My brother recommended I might like this web site. He was entirely right. This post actually made my day. You cann at imagine just how much time I had spent for this information! Thanks!

  15. You could definitely see your skills within the paintings you write. The arena hopes for more passionate writers such as you who aren at afraid to say how they believe. At all times follow your heart.

  16. Yo dude! Look up at the skies NATO is spraying fake clouds that are very toxic most clouds are not natural anymore, please research you will thank me for bringing this to your attention. PEACE.

  17. Thanks for another magnificent article. Where else could anyone get that kind of info in such an ideal way of writing? I have a presentation next week, and I am on the look for such information.

  18. Great post. I was checking constantly this blog and I am impressed!
    Extremely helpful info particularly the last part 🙂 I care for
    such information a lot. I was seeking this particular info for a
    long time. Thank you and good luck.

  19. Del mismo modo, el estrés y las inquietudes relacionadas con la salud mental pueden provocar disfunción eréctil o empeorarla. Siga todas las instrucciones en la etiqueta de su prescripción.

  20. That is a good tip especially to those fresh to the blogosphere.
    Brief but very precise info… Many thanks for sharing this one.
    A must read post!

  21. Great post however , I was wanting to know if you
    could write a litte more on this subject? I’d be very grateful if you could elaborate
    a little bit more. Cheers!

  22. Thanks for your marvelous posting! I actually enjoyed reading it,
    you are a great author.I will make sure to bookmark your blog and definitely will
    come back in the foreseeable future. I want
    to encourage that you continue your great writing, have a nice evening!

  23. hello there and thank you for your info – I have certainly
    picked up something new from right here. I did however expertise a few technical issues using this website, as I experienced
    to reload the website a lot of times previous
    to I could get it to load correctly. I had been wondering if your web host is
    OK? Not that I am complaining, but slow loading instances times will very
    frequently affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords.
    Anyway I am adding this RSS to my e-mail and could look out for a lot more of your respective exciting content.
    Ensure that you update this again very soon.

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

  25. Excellent goods from you, man. I have understand
    your stuff previous to and you’re just too wonderful. I actually like what you have acquired here, certainly like what you are stating and the way in which you say it.

    You make it enjoyable and you still care for to keep it wise.
    I can not wait to read much more from you. This is actually a great web site.

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

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

  28. I was recommended this web site by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are amazing! Thanks!

  29. Very nice post and straight to the point. I am not sure if this is actually the best place to ask but do you guys have any thoughts on where to hire some professional writers? Thank you

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

  31. I thought it was going to be some boring old post, but it really compensated for my time. I will publish a link to this page on my blog site. I am confident my visitors will locate that really useful

  32. This piece of writing on the topic of SEO provides clear idea for new SEO people that how to do Search engine optimization, so keep it up. Good work

  33. Source I like the valuable info you provide in your articles. I will bookmark your blog and check again here regularly. I am quite sure I all learn many new stuff right here! Good luck for the next!

  34. Nice blog here! Also your website rather a lot up very fast! What host are you the usage of? Can I am getting your associate link in your host? I want my website loaded up as fast as yours lol

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

  36. This particular blog is no doubt cool and diverting. I have discovered helluva interesting advices out of this amazing blog. I ad love to return over and over again. Thanks!

  37. Very nice info and right to the point. I am not sure if this is in fact the best place to ask but do you people have any ideea where to get some professional writers? Thank you

  38. What as Happening i am new to this, I stumbled upon this I ave found It absolutely helpful and it has helped me out loads. I hope to contribute & aid other users like its helped me. Good job.

  39. Nice blog here! Also your website loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

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

Please enter your comment!
Please enter your name here