Trong bài này ta sẽ tìm hiểu đến thao tác cuối cùng thường hay sử dụng trong MySQL lẫn PHP đó là cập nhật dữ liệu, đây là thao tác được dùng trong backend dùng để sửa thông tin sản phẩm, tin tức, chuyên mục, …

Cú pháp của lệnh update như sau:

1
2
3
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE some_column = some_value

Tương tự như trường hợp delete bạn phải truyền điều kiện update vào nếu không nó sẽ cập nhật cho toàn bộ records có trong table. Thông thường thì chúng ta lấy điều kiện theo khóa chính.

Nội dung chính

  • 1. Update dữ liệu với MySQLi
    • Sử dụng MySQLi Object-oriented:
    • Sử dụng MySQLi Procedural:
  • 2. Update dữ liệu với PDO
  • 3. Lời kết

1. Update dữ liệu với MySQLi

Tương tự như các thao tác trước chúng ta sẽ có hai trường hợp sử dụng.

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
// Kết nối CSDL
$conn = new mysqli('localhost', 'root', 'vertrigo', 'FreetutsDemo');
// Kiểm tra kết nối
if ($conn->connect_error) {
    die("Kết nối thất bại: " . $conn->connect_error);
}
// Lệnh update
$sql = "UPDATE News SET title='Tiêu đề updated' WHERE id=1";
// Thực hiện update
if ($conn->query($sql) === TRUE) {
    echo "update thành công";
} else {
    echo "Update 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
// Kết nối CSDL
$conn = mysqli_connect('localhost', 'root', 'vertrigo', 'FreetutsDemo');
// Kiểm tra kết nối
if (!$conn) {
    die("Kết nối thất bại: " . mysqli_connect_error());
}
// Lệnh update
$sql = "UPDATE News SET title='Tiêu đề updated' WHERE id=1";
// Thực hiện update
if (mysqli_query($conn, $sql)) {
    echo "update thành công";
} else {
    echo "Update thất bại: " . mysqli_error($conn);
}
// ngắt kết nối
mysqli_close($conn);

2. Update dữ liệu với 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
try {
    // Kết nối
    $conn = new PDO("mysql:host=localhost;dbname=FreetutsDemo", 'root', 'vertrigo');
    // Thiết lập Exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Câu SQL
    $sql = "UPDATE News SET title='Tiêu đề updated' WHERE id=1";
    // Prepared câu SQL
    $stmt = $conn->prepare($sql);
    // Thực thi câu SQL
    $stmt->execute();
    // Xuất kết quả tổng số record đã update
    echo $stmt->rowCount() . " records thành công";
}
catch (PDOException $e) {
    echo 'Lỗi'. "<br>" . $e->getMessage();
}
// Ngắt kết nối
$conn = null;

3. Lời kết

Các ví dụ trên chỉ demo cho các bạn nên mình không sử dụng prepared nên nếu bạn làm trong project thì nên sử dụng prepared đẻ truyền các giá trị vào các field cũng như ở trong điều kiện update nhé.

Bài này tới đây cũng gần như là bạn đã có đủ kiến thức để sử dụng PHP thao tác với CSDL MySQL rồi đấy, vì vậy mình sẽ tạm thời ngưng series này tại đây. Cám ơn các bạn đã theo dõi.

——————-#####——————-

393 BÌNH LUẬN

  1. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a
    comment is added I get three e-mails with the same comment.
    Is there any way you can remove me from that service?
    Thanks!

  2. You actually make it appear so easy with your presentation but I find this topic to be actually something which I feel I’d by no means understand.
    It seems too complicated and very huge for me. I am taking a look forward on your
    next publish, I’ll attempt to get the cling of it!

  3. Simply wish to say your article is as astonishing. The clearness in your post is simply spectacular
    and i could assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming
    post. Thanks a million and please carry on the rewarding work.

  4. Excellent post. I was checking continuously this weblog and I’m impressed!
    Very useful info particularly the final section 🙂 I deal with such info much.

    I was looking for this particular information for a very long time.
    Thank you and best of luck.

  5. Have you ever thought about including a little bit more than just your articles?
    I mean, what you say is fundamental and everything. But just
    imagine if you added some great photos or videos to give
    your posts more, “pop”! Your content is excellent but with pics and clips,
    this site could definitely be one of the most beneficial in its niche.
    Excellent blog!

  6. I do nott even know how I ended up here, but I thought
    this post was great. I don’t know who you are but certainly you’re going to
    a famous bloggerr if you are not already 😉 Cheers!

  7. Hello, i think that i saw you visited my weblog so i came to “return the
    favor”.I am trying to find things to enhance my website!I suppose its ok to
    use some of your ideas!!

  8. Good day! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa?
    My blog addresses a lot of the same subjects as yours and I
    think we could greatly benefit from each other. If you are interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Awesome blog by the way!

  9. Wonderful article! This is the type of info that are meant to be shared around the web.
    Shame on Google for no longer positioning this post upper!
    Come on over and discuss with my web site . Thanks =)

  10. I am now not sure the place you are getting your info, but good topic.
    I needs to spend some time finding out more or working out more.
    Thank you for magnificent info I used to be on the lookout for
    this info for my mission.

  11. Thank you for the good writeup. It in truth was once a amusement account it.
    Look advanced to more brought agreeable from you!
    However, how could we keep in touch?

  12. Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog
    to rank for some targeted keywords but I’m not seeing very good success.
    If you know of any please share. Cheers!

  13. Whoa! This blog looks exactly like my old one!

    It’s on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!

  14. It’s appropriate time to make a few plans for the future and
    it’s time to be happy. I have learn this submit and if I could I
    wish to suggest you few fascinating things or tips.
    Maybe you could write subsequent articles referring
    to this article. I wish to learn even more things about it!

  15. I don’t even know the way I finished up right here,
    however I thought this post used to be good. I don’t recognize who
    you might be but certainly you are going to a well-known blogger in the event you aren’t already.
    Cheers!

  16. Usually I do not read article on blogs, however I would like to say that this write-up very pressured me to try and do so! Your writing taste has been amazed me. Thanks, quite great post.

  17. Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is wonderful, as well as the content!. Thanks For Your article about &.

  18. Rattling superb information can be found on web blog. It is fast approaching the point where I don at want to elect anyone stupid enough to want the job. by Erma Bombeck.

  19. Woman of Alien Great perform you have got done, this great site is admittedly great with great facts. Time is God as strategy for trying to keep anything from taking place directly.

  20. Wow, wonderful blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is great, let alone the content!. Thanks For Your article about sex.

  21. Woman of Alien Great do the job you ave carried out, this website is de facto interesting with amazing information. Time is God as method of preserving everything from occurring at once.

  22. IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžd ought to talk to you here. Which is not some thing I do! I quite like reading a post which will make individuals believe. Also, many thanks permitting me to comment!

  23. Your style is really unique in comparison to other folks I have read stuff from. Thank you for posting when you ave got the opportunity, Guess I all just book mark this page.

  24. Wow, wonderful blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is excellent, let alone the content!. Thanks For Your article about sex.

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

  26. What as up everybody, here every person is sharing such knowledge, therefore it as nice to read this blog, and I used to pay a quick visit this website everyday.

  27. It as really a nice and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us up to date like this. Thank you for sharing.

  28. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone
    to do it for you? Plz reply as I’m looking to construct
    my own blog and would like to find out where u got
    this from. many thanks

  29. I was suggested this web site through my cousin. I’m not sure whether or not this submit is
    written via him as no one else know such special approximately my problem.

    You are incredible! Thanks!

  30. Hello There. I found your blog using msn. This is an extremely well written article.
    I will be sure to bookmark it and come back to read more of
    your useful info. Thanks for the post. I’ll certainly comeback.

  31. I was recommended this web position by my cousin. I am not sure whether this post is written by him as rejection one to boot get such detailed concerning my problem. You are amazing! Thanks!

  32. This particular blog is really interesting and also amusing. I have chosen many handy tips out of this blog. I ad love to come back again and again. Thanks a lot!

  33. Wow, wonderful blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is great, let alone the content!

  34. This unique blog is no doubt entertaining and also informative. I have chosen many helpful advices out of this amazing blog. I ad love to return over and over again. Thanks!

  35. I will right away seize your rss feed as I can at to find your e-mail subscription link or e-newsletter service. Do you have any? Kindly let me know so that I could subscribe. Thanks.

  36. Wow! This could be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Wonderful. I am also a specialist in this topic so I can understand your effort.

  37. Sweet blog! I found it while searching 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

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

  39. It’а†s actually a nice and helpful piece of info. I am satisfied that you simply shared this useful information with us. Please stay us up to date like this. Thank you for sharing.

  40. I simply could not depart your site before suggesting that I actually enjoyed the standard info a person provide on your guests? Is gonna be back incessantly in order to check up on new posts.

  41. I’а†ve read several excellent stuff here. Certainly value bookmarking for revisiting. I surprise how so much attempt you set to make one of these fantastic informative web site.

  42. I take pleasure in, lead to I found just what I used to be taking a look for. You ave ended my four day long hunt! God Bless you man. Have a nice day. Bye

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

  44. My brother suggested I might like this web site. He was totally right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks!

  45. My brother suggested I might like this web site. He was totally right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks!

  46. Wow! This can be one particular of the most useful blogs We have ever arrive across on this subject. Actually Magnificent. I am also an expert in this topic therefore I can understand your hard work.

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

Please enter your comment!
Please enter your name here