search
HomeBackend DevelopmentPHP TutorialDifferences and connections between the three main APIs commonly used in link-MySQL database servers in php: mysql, mysqli, pdo

Differences and connections between the three main APIs when php connects to the mysql database server: mysql, mysqli, and pdo
are also commonly used extensions. Which of them has better performance?

In fact, they are all good, but in comparison some are better (I like pdo)
  1. /**
  2. After reading a lot of related database connections and operations, here is a summary of database connections in
  3. php
  4. --------------------- I hope it will be helpful
  5. */
  6. //1 Connection type
  7. /**
  8. Differences and connections between the three main APIs commonly used in link-MySQL database servers in php: mysql, mysqli, pdo
  9. /********Basic related information*********/
  10. a.API---------- ------Application Programming Interface
  11. Application Programming Interface (abbreviation of Application Programming Interface) defines classes, methods, functions,
  12. variables, and so on, everything that needs to be called in your application to complete specific tasks. When a PHP application needs to interact with a database, the API required is usually exposed through a PHP extension (called by the terminal PHP programmer).
  13. API can be process-oriented or object-oriented. For procedure-oriented APIs, we complete tasks by calling functions, while for object-oriented APIs, we instantiate classes and call methods on the objects obtained after instantiation.
  14. Of the two interfaces, the latter is usually preferred as it is more modern and gives us a good
  15. code structure.
  16. b.connector ----- "A piece of software code that allows your application to connect to the MySQL database server".
  17. When your PHP application needs to interact with a database server, you need to write PHP code to complete a series of activities such as "connecting to the data
  18. library server", "querying the database" and other database-related functions. Your PHP application will use software that provides these APIs, or use some intermediate libraries when needed, to handle the interaction between your application and the database server.
  19. c. Driver
  20. Software code used to interact with a specific type of database server. The driver may call some libraries,
  21. such as MySQL client library or MySQL Native driver library. These libraries implement the low-level protocols for interacting with the MySQL database server.
  22. Maybe people use the terms connector and driver without distinction.
  23. The term "driver" in MySQL related documentation is used as a connector package
  24. that provides software code for a specific database part.
  25. d. What are extensions?
  26. You will also find many other extensions in the PHP documentation. PHP code is composed of a core and some optional extensions that make up the core functionality.
  27. MySQL-related extensions of PHP, such as mysqli and mysql, are all implemented based on the PHP extension framework.
  28. A typical function of extension is to expose an API to PHP programmers, allowing extended functions to be used by programmers.
  29. Of course, there are also some extensions developed based on the PHP extension framework that do not expose API interfaces to PHP programmers.
  30. For example, the PDO MySQL driver extension does not expose the API interface to PHP programmers, but provides an interface to the PDO layer above it.
  31. The terms API and extension do not describe the same kind of thing, because extensions may not need to expose an API interface to programmers.
  32. /*********Key points*******/
  33. Main API for MySQL provided in PHP:
  34. ■MySQL extension for PHP
  35. (pros and cons)
  36. [
  37. Designed and developed to allow PHP applications to interact with MySQL databases Early expansion. The mysql extension provides a procedure-oriented interface,
  38. and is designed for MySQL4.1.3 or earlier. Therefore, although this extension can interact with MySQL 4.1.3 or newer database servers, it does not support some features provided by later MySQL servers.
  39. ■Mysqli extension for PHP
  40. The mysqli extension, which we sometimes call the MySQL enhancement extension, can be used to use the new advanced features in MySQL 4.1.3 or newer versions.
  41. The mysqli extension is included in PHP 5 and later versions.
  42. The mysqli extension has a series of advantages. Compared with the mysql extension, the main improvements are:
  43. ■Object-oriented interface
  44. ■Prepared statement support (Annotation: Please refer to mysql related documents for prepare)
  45. ■Multiple statement execution support
  46. ■Transaction support
  47. ■Enhanced debugging capabilities
  48. ■Embedded service support
  49. ■PHP Data Object (PDO)
  50. PHP Data Object is a database abstraction layer specification in PHP applications. PDO provides a unified API interface that allows your PHP application to not care about the specific database server system type to be connected. In other words,
  51. If you use PDO's API, you can seamlessly switch database servers whenever needed
  52. /*******Compared***********/
  53. PHP-MySQL is the most original Extension for PHP to operate the MySQL database. The i in PHP-MySQLi stands for Improvement, which provides relatively advanced functions. As far as the Extension is concerned, it also increases security.
  54. And PDO (PHP Data Object) provides an Abstraction Layer to operate the database
  55. Detailed source reference: http://www.jb51.net/article/28103.htm
  56. 1.mysql and mysqli
  57. mysqli It is a new function library provided by php5. (i) means improvement, and its execution speed is faster. Of course, it is also safer. Detailed source reference: http://www.jb51.net/article/28103.htm
  58. mysql is non-persistent Connection function and mysqli is a permanent connection function. In other words,
  59. mysql will open a connection process every time it is connected, and mysqli will use the same connection process when running mysqli multiple times,
  60. thus reducing the server overhead.
  61. Some friends use new mysqli('localhost', usenamer when programming) ', 'password', 'databasename'); always reports an error, Fatal error: Class 'mysqli' not found in d:...
  62. Isn't the mysqli class included in PHP?
  63. It is not enabled by default. Under win, you need to change php.ini and remove the ";" before php_mysqli.dll. Under Linux, you need to compile mysqli into it.
  64. 1: Mysqli.dll allows the database to be operated in an object or process, and its use is also very easy. Here are a few common
  65. detailed sources for reference: http://www.jb51.net/article/28103.htm
  66. Do more and talk less:
  67. */
  68. mysql_connect($db_host, $db_user, $db_password);
  69. mysql_select_db($dn_name);
  70. $result = mysql_query("SELECT `name` FROM `users` WHERE `location` = '$location'");
  71. while ($row = mysql_fetch_array($result, MYSQL_ASSOC ))
  72. {
  73. echo $row['name'];
  74. }
  75. mysql_free_result($result);
  76. /**
  77. In fact, there is some knowledge behind it...
  78. This method cannot Bind Column, speaking from the previous SQL description , $location is prone to SQL Injection.
  79. Later, mysql_escape_string() (note: deprecated after 5.3.0) and mysql_real_escape_string()
  80. were developed to solve this problem. However, if this is done, the entire narrative will become complicated and ugly, and if there are too many columns, You can imagine what the situation will be like...
  81. Detailed source reference: http://www.jb51.net/article/28103.htm
  82. */
  83. $query = sprintf("SELECT * FROM users WHERE user ='%s' AND password='%s'",
  84. mysql_real_escape_string($user),
  85. mysql_real_escape_string($password));
  86. mysql_query($query);
  87. /**
  88. There has been a lot of progress in PHP-MySQLi. In addition to solving the above problems through Bind Column, it also supports Transaction and Multi Query.
  89. It also provides Object oriented style (the following PHP-MySQLi example is written) and Procedural style
  90. (the way of writing the PHP-MySQL example above) are two ways of writing...and so on.
  91. Detailed source reference: http://www.jb51.net/article/28103.htm
  92. */
  93. $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
  94. $sql = "INSERT INTO `users` (id, name, gender, location) VALUES (?, ?, ?, ? )" ;
  95. $stmt = $mysqli->prepare($sql);
  96. $stmt->bind_param('dsss', $source_id, $source_name, $source_gender, $source_location);
  97. $stmt->execute () ;
  98. $stmt->bind_result($id, $name, $gender, $location);
  99. while ($stmt->fetch())
  100. {
  101. echo $id . $name . $gender . $location;
  102. }
  103. $stmt->close();
  104. $mysqli->close();
  105. /**
  106. But I found some shortcomings here. For example, Bind Result is a bit redundant, but it doesn’t really matter.
  107. Because the biggest problem is that this is not an abstraction method, so when the backend When changing the database, the pain begins...
  108. So PDO appeared
  109. Detailed source reference: http://www.jb51.net/article/28103.htm
  110. */
  111. // 2.PDO and mysql
  112. /*
  113. PDO is PHP5. Supported only after 1, it uses a consistent interface for accessing the database. However, many domestic open source programs use the functions provided by MySQL extension to connect to the database and perform queries. PDO is so powerful, why don’t mature domestic PHP systems use it?
  114. I asked a few friends why they use PDO, and the answer is "fast". Will PDO connect to the database faster? Why use PDO?
  115. What are the differences between the two methods? First of all, I am more concerned about performance issues. I wrote a script to test inserting 1 million pieces of data into MySQL.
  116. */
  117. $link = mysql_connect("localhost", "root", "root") or die('mysql connect error');
  118. $num = 100000;
  119. $dsn = "mysql:host=127.0.0.1 ;dbname=performace_test";
  120. $db = new PDO($dsn, 'root', 'root', array(PDO::ATTR_PERSISTENT => true));
  121. mysql_query('TRUNCATE TABLE `performace_test`.`myquery` ',$link); //Truncate Table
  122. $query = "INSERT INTO `performace_test`.`myquery`(`goods_id`,`cat_id`,`click_count`,`goods_number`,`goods_weight`,`goods_sn`,` goods_name`,`goods_reason`,`brand_name`,`goods_thumb`,`brand_id`,`is_on_sale`,`wap_cod`,`wap_title`,`wap_detail`,`wap_flag`,`wap_onsale`,`shop_price`,`cost_price` ,`channel_rate`,`channel_onsale`,`add_time`,`is_main`,`last_update`,`brand_logo`) VALUES ( '80′,'298′,'65′,'100′,'0.125′,'SMT000080′ ,'Health',",'Health120','images/201004/thumb_img/80_thumb_G_1272071721054.jpg','1′,'0′,'0′,NULL,NULL,NULL,'0′,'2980.00′, '0.00′,'1.250000′,'1′,'1271612064′,'0′,'1297624384′,'1293649512083026412.jpg')";
  123. $start_time = microtime(true);
  124. for($i=0;$ i{
  125. mysql_query($query,$link);
  126. }
  127. echo "USE MySQL extension: ". (microtime(true)-$start_time);
  128. mysql_query('TRUNCATE TABLE `performace_test` .`myquery`',$link); //Truncate Table
  129. $start_time = microtime(true);
  130. for($i=0;$i{
  131. $db->exec( $query);
  132. }
  133. echo "rnUSE PDO: ". (microtime(true)-$start_time);
  134. /**
  135. USE MySQL extension: 95.233189106s
  136. USE PDO: 99.1193888187s
  137. Almost on linked MySQL no difference. The performance penalty of PDO is completely negligible.
  138. But there are a lot of operations that the MySQL extension library does not have:
  139. 1: PDO is truly a unified interface database operation interface implemented at the bottom layer
  140. 2: PDO supports more advanced DB feature operations, such as: Scheduling of stored procedures, etc., is not supported by the mysql native library.
  141. 3: PDO is PHP’s official PECL library, and its compatibility and stability must be higher than MySQL Extension. You can directly use the pecl upgrade pdo command to upgrade
  142. PHP6 is also used by default PDO performs database linking, and MySQL Extension will assist.
  143. So in our daily projects, if the environment permits, we try to use PDO to perform MySQL database operations as much as possible.
  144. ?>
Copy code

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.