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.

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
