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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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),