One:
PHP-MySQL is the original Extension for PHP to operate the MySQL database. The i of PHP-MySQLi represents Improvement, which provides relatively advanced functions. As far as the Extension is concerned, it also increases security. PDO (PHP Data Object) provides an Abstraction Layer to operate the database. In fact, you can’t tell the difference in practical terms, so just look at the program...
First, let’s look at a paragraph written in PHP-MySQL Program code, such examples are commonly used around the world:
The code is as follows:
mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($dn_name);
$result = mysql_query(" SELECT `name` FROM `users` WHERE `location` = '$location'");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo $row['name'];
}
mysql_free_result ($result);
?>
There is nothing wrong at first glance, but there is actually some knowledge behind it...
This method cannot Bind Column. In terms of the previous SQL description, $location is prone to SQL Injection. Later, mysql_escape_string() (note: deprecated after 5.3.0) and mysql_real_escape_string() were developed to solve this problem. However, the entire narrative will become complicated and ugly, and if there are too many fields, you can Imagine what it would be like...
The code is as follows:
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user ) ,
mysql_real_escape_string($password));
mysql_query($query);
?>
has made a lot of progress in PHP-MySQLi. In addition to solving the above problems through Bind Column, it also supports Transaction, Multi Query, and also provides two writing methods: Object oriented style (the writing method of the PHP-MySQLi example below) and Procedural style (the writing method of the PHP-MySQL example above)... and so on.
The code is as follows:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
$sql = "INSERT INTO `users` (id, name, gender, location) VALUES (?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('dsss', $source_id, $source_name, $source_gender, $source_location) ;
$stmt->execute();
$stmt->bind_result($id, $name, $gender, $location);
while ($stmt->fetch())
{
echo $id . $name . $gender . $location;
}
$stmt->close();
$mysqli->close();
?>
But I found some shortcomings here, such as Bind Result, this is a bit redundant, but it actually doesn't matter, because the biggest problem is that it is not an abstraction method, so when the backend changes the database, the pain begins...
So PDO It appears (Note: Currently, for Ubuntu and Debian, PDO does not have a direct package to install, but must be installed through PECL).
The code is as follows:
roga@carlisten-lx:~$ pecl search pdo
================================ ========
Package Stable/(Latest) Local
PDO 1.0.3 (stable) PHP Data Objects Interface.
PDO_4D 0.3 (beta) PDO driver for 4D-SQL database
PDO_DBLIB 1.0 (stable) FreeTDS/ Sybase/MSSQL driver for PDO
PDO_FIREBIRD 0.2 (beta) Firebird/InterBase 6 driver for PDO
PDO_IBM 1.3.2 (stable) PDO driver for IBM databases
PDO_INFORMIX 1.2.6 (stable) PDO driver for IBM Informix INFORMIX databases
PDO_MYSQL 1.0 .2 (stable) MySQL driver for PDO
PDO_OCI 1.0 (stable) Oracle Call Interface driver for PDO
PDO_ODBC 1.0.1 (stable) ODBC v3 Interface driver for PDO
PDO_PGSQL 1.0.2 (stable) PostgreSQL driver for PDO
PDO_SQLITE 1.0 .1 (stable) SQLite v3 Interface driver for PDO
pdo_user 0.3.0 (beta) Userspace driver for PDO
Once installed through PECL, you can operate the database in the following ways:
The code is as follows:
$dsn = "mysql:host=$db_host;dbname=$db_name";
$dbh = new PDO($dsn, $db_user, $db_password);
$sql = "SELECT `name`, `location` FROM `users` WHERE `location` = ? , `name` = ?";
$sth = $dbh->prepare($sql);
$sth->execute(array($location, $ name));
$result = $sth->fetch(PDO::FETCH_OBJ);
echo $result->name . $result->location;
$dbh = NULL;
?>
zar It seems that PDO's program code is not shorter, so what are the benefits?
1. When PDO connects to a database, it uses Connection String to determine which database to connect to.
2. PDO can use PDO::setAttribute to determine the connection settings, such as Persistent Connection, and the way to return errors (Exception, E_WARNING, NULL). Even the case of the returned field name...etc.
2. PDO supports the Bind Column function. In addition to the basic Prepare and Execute, you can also Bind a single column and specify the column type.
4. PDO is an Abstraction Layer, so even if you change the storage medium, the effort required is minimal in comparison.
Unfortunately, even though these things have been around for a long time, they are still not popular enough. I think it may be because people are accustomed to reading books on the market, but those books often only introduce the simplest and most traditional methods. As a result, many people still use MySQL to directly connect to the database.
However, at present, I personally still like to connect to the database through DBI, such as ActiveRecord and Propel ORM (Object-Relational Mapping).
For example, taking ActiveRecord as an example, if you want to implement such a SQL statement...
INSERT INTO `users` (id, name, gender, location) VALUES(1, 'roga', 'male', 'tpe')
Use PDO To write:
The code is as follows:
$sql = "INSERT INTO `users` (id, name, gender, location) VALUES(?, ?, ?, ?)";
$sth = $ dbh->prepare($sql);
$sth->execute(array(1, 'roga', 'male', 'tpe'));
?>
But in terms of ActiveRecord, then Yes:
The code is as follows:
$user = new User();
$user->id = 1;
$user->name = 'roga';
$user->gender = 'male';
$user->location = 'tpe';
$user->save();
?>
Isn't the latter much simpler in syntax, and it also greatly reduces the need for SQL Language dependency! (For questions about SQL implementations in different databases, please refer to Comparison of different SQL implementations) The above are some simple introductions. If there are any omissions and fallacies, you are welcome to add.
mysql is a non-persistent connection function and mysqli is a permanent connection function. In other words,
mysql will open a connection process every time it is connected, and running mysqli multiple times will use the same connection process, thereby reducing server overhead.
Some friends use new mysqli('localhost', usenamer' when programming , 'password', 'databasename'); always reports an error, Fatal error: Class 'mysqli' not found in d:... Isn't the mysqli class included in PHP?
It is not enabled by default. Under win, you need to change php.ini and remove the ";" in front of php_mysqli.dll. Under Linux, you need to compile mysqli into it.
1: Mysqli.dll allows the database to be operated in an object or process, and its use is also very easy. Here is a comparison between several common operations and mysql.dll.
1: mysql.dll (can be understood as a functional way):
The code is as follows:
$conn = mysql_connect('localhost', 'user', 'password'); //Connect to the mysql database
mysql_select_db('data_base '); //Select the database
$result = mysql_query('select * from data_base');//There is a second optional parameter here to specify the open connection
$row = mysql_fetch_row( $result ) ) //For Simple, here we only take one row of data
Echo $row[0]; // Output the value of the first field
Mysqli also has a procedural method, but it just starts with the mysqli prefix, and everything else is almost the same. If mysqli operates in a procedural manner, some functions must specify resources, such as mysqli_query (resource identifier, SQL statement), and the parameter of the resource identifier is placed in front, while the parameter of mysql_query (SQL statement, 'optional') The resource identifier is placed at the end and does not need to be specified. It defaults to the last opened connection or resource.
2mysqli.dll (object mode):
The code is as follows:
$conn = new mysqli('localhost', 'user', 'password','data_base');
//The connection here is new, and finally One parameter is to directly specify the database, no need for mysql_select_db()
//You can also not specify it when constructing, then $conn -> select_db('data_base')
$result = $conn -> query( 'select * from data_base ' );
$row = $result -> fetch_row(); //Get a row of data
echo row[0]; //Output the value of the first field
Two: mysql_fetch_row(),mysql_fetch_array()
This Both functions return an array. The difference is that the array returned by the first function only contains values. We can only read data using array subscripts $row[0],
$row[1]. , and the array returned by mysql_fetch_array() contains both the first type and the form of key-value
pairs. We can read the data like this, (if the database fields are username, passwd):
$row['username'], $row['passwd']
Furthermore, if you use ($row as $kay => $value) to operate, you can also directly obtain the field name of the database.
What’s more important is that mysqli is a new function library provided by php5. (i) represents an improvement and its execution speed is faster.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

Atom editor mac version download
The most popular open source editor