PHP has supported MySQL since its early days, and included an API in its second version. Because the combination of the two is so common, this extension is enabled by default. However, PHP 5 released a newer MySQL extension called MySQL Improved, or mysqli for short.
Why release a new extension? The reasons are twofold. First, MySQL is evolving rapidly, and users who rely on older extensions are unable to take advantage of new features such as prepared statements, advanced connection options, and security improvements. Second, while the old extension was certainly fine to use, many people considered the procedural interface obsolete and preferred the object-oriented interface for not only tighter integration with other applications but the ability to extend it as needed. interface. To address these shortcomings, the MySQL developers decided it was time to revamp that extension, not only modifying the internal behavior to improve performance, but also introducing additional features that facilitate the use of features available in newer versions of MySQL.
Several key improvements:
# Object-oriented: MySQL extensions are encapsulated into a series of classes, thus encouraging the use of a programming paradigm that many people consider to be more convenient and efficient than PHP's traditional procedural approach. But those who prefer the procedural paradigm don't worry, because it also provides a traditional procedural interface.
# prepared statements: Can prevent SQL injection attacks. It eliminates the overhead and inconvenience of those queries that are executed repeatedly.
# Transaction support: Although PHP's original MySQL extension can also support transaction functions, the mysqli extension provides an object-oriented interface to these functions.
# Enhanced debugging capabilities: The mysqli extension provides many methods for debugging queries, making the development process more efficient.
# Embedded server support: MySQL 4.0 release introduces an embedded MySQL server library, so interested users can run a complete MYSQL server in client applications such as desktop applications. The mysqli extension provides methods for connecting to and operating on these embedded MySQL servers.
# Master/slave support: Starting from MySQL 3.23.15, MySQL provides support for replication. Using the mysqli extension, you can ensure that queries are routed to the master server in a replicated configuration.
Those users who are familiar with the original MySQL extension will find the enhanced mysqli extension very familiar, with almost the same naming convention. For example, the database connection function is called mysqli_connect instead of mysql_connect.
1. Prerequisites for installation
Starting from PHP 5, MySQL support is not bundled with the standard PHP distribution package. Therefore, PHP needs to be configured explicitly to take advantage of this extension.
1.1. Enable mysqli extension in Linux/UNIX
Use the --with-mysqli flag when configuring PHP. It should point to the location of the mysql_config program in MySQL 4.1 and later.
1.2. To enable the mysqli extension on Windows
You need to modify php.ini and uncomment this line: extension=php_mysqli.dll. If not, add this line. Of course, before enabling any extension, make sure that PHP's extension_dir directive points to the appropriate directory.
1.3. Use MYSQL local driver
For a long time, PHP requires that the MySQL client library be installed on the server running the PHP program, regardless of whether the MYSQL server happens to be local or elsewhere. PHP 5.3 removes this requirement and introduces a new MySQL driver called MySQL Native Driver, also called mysqlnd, which has many advantages over the driver just mentioned. It is not a new API, but a new "conduit" that existing APIs (mysql, mysqli, PDO_MySQL) can utilize to communicate with a MySQL server. It is recommended to use mysqlnd instead of other drivers (unless you have a very good reason).
To use mysqlnd with an extension, you need to recompile PHP, for example: --with-mysqli=mysqlnd. You can also specify a few more, such as %>./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd. The mysqlnd driver also has some restrictions. Currently it does not provide compression or SSL support.
1.4. Managing user permissions
When a script initializes a connection to the MySQL server, permissions are passed and verified. The same is true when submitting commands that require permission verification. However, you only need to confirm the execution user when connecting; subsequent executions of the script will always be that user unless a new connection is made later.
1.5. Use sample data
It’s easy to add some examples when learning new knowledge. Database: corporate; table: products
CREATE TABLE products (
id INT NOT NULL AUTO_INCREMENT,
sku VARCHAR(8) NOT NULL,
name VARCHAR(100) NOT NULL,
price DECIMAL(5,2 ) NOT NULL,
PRIMARY KEY(id)
)
==================================== ========================================
2. Use mysqli extension
2.1 , establish and disconnect connections
First connect to the server, then select a database, and then close the connection. Object-oriented and procedural are both possible styles.
To use the object-oriented interface to interact with the MySQL server, you must first instantiate it using the constructor of the mysqli class.
mysqli([string host [, string username [, string pswd
] ) Many parameters of the function are the same as the traditional mysql_connect() function.
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
If at some point, you want to switch to another server or choose another database, you can use connect() and select_db() method. The parameters of the connect() method are the same as the constructor of the mysqli class.
// Instantiate the mysqli class
$mysqli = new mysqli();
// Connect to the database server and select a database
$mysqli->connect('localhost', 'root', '' , 'corporate');
------------------------------------------------ ----------------------------------------
or
// Connect to the database server
$mysqli = new mysqli('localhost', 'catalog_user', 'secret');
// Select the database
$mysqli->select_db('corporate');
Once the script is completed When executed, any open database connections are automatically closed and resources are restored. However, it is also possible that a page needs to use multiple database connections during execution, and these connections need to be closed correctly. Even if only one connection is used, it is a good practice to close it at the end of the script. $mysqli->close().
2.2. Handling connection errors
Connection errors should be carefully monitored and countermeasures taken accordingly. The mysqli extension provides some features that can be used to catch error messages. Another way is to use exceptions. For example, mysqli_connect_errno() and mysqli_connect_error() can be used to diagnose and display MySQL connection error messages.
2.3. Get the error message
2.3.1. Get the error code
errno() method returns the error code generated during the last MySQL function execution. 0 means no errors.
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', 'corporate');
printf("Mysql error number generated: %d", $mysqli-> errno);
?>
2.3.2. Get the error message
error() method returns the most recently generated error message. If there is no error, an empty string is returned. The messaging language relies on the Mysql database server.
2.4. Store connection information in a separate file
In terms of secure programming practices, it is a good idea to change passwords regularly. There are also many scripts that need to access the database, and it is too troublesome to modify them one by one. The solution is to store it in a separate file and include it in your current file if necessary.
For example, you can put the mysqli constructor in a header file (mysql.connect.php):
$mysqli = new mysqli('localhost', 'catalog_user', 'secret', ' corporate');
?>
Then include it in other files:
include 'mysql.connect.php';
// begin database selection and queries.
?> ;
==================== Not finished yet, to be continued
The above has introduced the use of PHP and MySQL, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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 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 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 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.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools