您的位置 首页 php

Mysqli的基本操作-CURD的学习开发总结

PHP自5.5起,已经完全废除mysql扩展,官方推荐使用MySQLI或PDO来代替。这篇文章主要讲mysqli的一些基本操作。使用mysqli有两个风格的写法,对象式或函数式,下面我们只展示函数式的写法风格。

数据库连接

首先肯定需要连接数据库。连接数据前,我们需要准备的一般有数据库的账号、密码、端口号、数据库名。

因为网络原因或其他原因经常会有连接不上数据库的情况,所以,我们需要做连接失败的处理。

<?php// 数据库连接$mysqli = mysqli_connect(   'localhost',   'root',   '',   'test');if (mysqli_connect_errno()) {   throw new Exception('databases connect error:'       .mysqli_connect_error());}// ...一些数据库操作// 关闭数据库资源mysqli_close($mysqli);

设置字符集

设置字符集使用mysqli_set_charset();

字符集目前我们大都使用utf8mb4,因为他支持4个字节长度的字符。他支持一些emoji表情字符。当然如果你不需要支持4字节字符的话可以选择使用utf8,因为他比较剩空间。

mysqli_set_chartset($mysqli, 'utf8mb4');

重新选择数据库

数据库连接后,还可以重新选择数据库。

mysqli_select_db($mysqli, '数据库名');

CURD操作

mysqli_query():对数据库执行一次操作,DDL、DQL 、DML都支持。

mysqli_affected_rows():获取影响记录行数。

新增数据操作

mysqli_query($mysqli,   "INSERT INTO users(username, age, sex)               VALUES('周杰伦', 35, '男'),                      ('谢霆锋', 35, '男')");if (mysqli_affected_rows($mysqli) <= 0) {   throw new Exception('databases insert error:'       . mysqli_error($mysqli));}

修改数据操作

这里面有一个注意点,mysqli_affected_rows返回的值为0的情况。它更新的信息与上次完全一样,这个情况很普遍。比如说在修改的时候,连续点击了多次修改按钮。但并不能说明程序代码有问题。所以,和新增不一样的是,返回0也应该是成功状态。

mysqli_query($mysqli,   "UPDATE users SET age=40 WHERE user_id = 1");if (mysqli_affected_rows($mysqli) < 0) {   throw new Exception('databases update error:'       . mysqli_error($mysqli));}

删除数据操作

注意:修改和删除操作必须加where条件,不然将会修改整个表的数据,后果不堪设想(删库跑路o(╯□╰)o)。

mysqli_query($mysqli,   "Delete FROM users  WHERE user_id = 100");if (mysqli_affected_rows($mysqli) <= 0) {   throw new Exception('databases delete error:'       . mysqli_error($mysqli));}

查询操作

当mysqli_query执行的是一条查询语句时,该函数会返回mysqli_result结果集。

mysqli_fetch_all()从结果集中获取全部数据。该函数第二个参数可以指定返回数据的格式。分别为:

  • MYSQLI_NUM:返回索引数组

  • MYSQLI_ASSOC:返回关联数组

  • MYSQLI_BOTH:既有索引数组也有关联数组

另外需要注意,对结果集的操作结束后,记得销毁结果集资源。

// 数据库连接$mysqli = mysqli_connect(   'localhost',   'root',   '',   'test');if (mysqli_connect_errno()) {   throw new Exception('databases connect error:'       .mysqli_connect_error());}mysqli_set_charset($mysqli, 'utf8mb4');$result = mysqli_query($mysqli,   "SELECT * FROM users");if (mysqli_affected_rows($mysqli) < 0) {   throw new Exception('databases select error:'       . mysqli_error($mysqli));}$users = mysqli_fetch_all($result, MYSQLI_ASSOC);// 销毁结果集资源mysqli_free_result($result);// 关闭数据库资源mysqli_close($mysqli);

以上就是Mysqli基本操作,个人实际学习开发总结,欢迎讨论!

以上就是Mysqli的基本操作-CURD的学习开发总结的详细内容,更多请关注求知技术网其它相关文章!

文章来源:智云一二三科技

文章标题:Mysqli的基本操作-CURD的学习开发总结

文章地址:https://www.zhihuclub.com/1278.shtml

关于作者: 智云科技

热门文章

评论已关闭

24条评论

  1. Iusto harum officiis qui qui temporibus exercitationem. Magni pariatur earum porro qui. Eum modi asperiores unde amet vel nostrum perspiciatis. Moyna Artemis Aalst

  2. Everything is very open with a very clear explanation of the issues. It was really informative. Your site is extremely helpful. Thanks for sharing! Sarine Wilburt Sadira

  3. Hello there! I just want to give you a big thumbs up for the excellent info you have got right here on this post. I will be returning to your website for more soon. Terra Jefferey Voccola

  4. Superb review. Indeed, our little collective was part of the Faviken theatre. To be savoured. Feliza Darcy Faust

  5. There is noticeably a bundle to find out about this. I think you made sure great factors in functions also. Stephenie Adolphe Michail

  6. Simply wish to say your article is as astounding. The clearness in your post is simply spectacular and i could assume you are an expert on this subject. Fine with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding work.| Lanie Sibyl Lynus

  7. Thank you a lot for providing individuals with a very wonderful opportunity to check tips from here. It really is very pleasurable and full of fun for me and my office friends to visit your site at least 3 times a week to study the fresh items you have got. Of course, I am also always satisfied with your good concepts served by you. Some 1 facts on this page are undoubtedly the simplest I have had. Annemarie Heriberto Beedon

  8. Thanks for the good writeup. It if truth be told used to be a amusement account it. Mel Dorie Romola

  9. Barb, just use the dry cake mix, add it to a bowl, add in the spices and stir and then stir in the pumpkin and raisins. Adelaida Robby Dorolisa

  10. I am so happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that is at the other blogs. Appreciate your sharing this greatest doc. Leena Nobie Adham

  11. Some us know just about all concerning the compelling moderate you present powerful methods on this web site and for that reason strongly encourage contribution through other ones on this particular subject while our very own child is really discovering a new great deal. Have enjoyment with the portion regarding the year. Lorry Danny Tu

  12. Thanks for cleaning up done by those heroes-workers and volunteers Verena Jase Asel

  13. Fake temp mail is a service that allows you to move more comfortably in the internet environment. You can choose fake mail alternatives for membership and subscription applications of websites. Today, many websites require membership. However, this situation causes your mailbox to be filled with spam mails. Protempmail.com also saves you from the hassle of mandatory membership.

  14. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus

  15. Read your books everyday, then your knowledges will be increased Bathsheba Sheridan Branch

  16. Attractive component of content. I simply stumbled upon your website and in accession capital to say that I get in fact loved account your blog posts.otto von muller

  17. I was studying some of your posts on this website and I think this website is rattling informative ! Keep on putting up. rainer werner fassbinder

  18. After examine a couple of of the blog posts on your web site now, and I truly like your approach of blogging. I bookmarked it to my bookmark website checklist and will likely be checking again soon. Pls check out my website online as properly and let me know what you think.

  19. There is certainly a great deal to find out about this issue. I like all the points you made.

  20. Looking forward to reading more. Great post. Really looking forward to read more. Cool. Alex.

网站地图