Difference: 1. PDO is used in 12 different databases, while MySQLi is only used in the mysql database; 2. The way PDO closes the connection is "$conn = null", while the way MySQLi closes the connection is "$conn->close()" or "mysqli_close()".
The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.
After php5.3 version, there are two ways to connect to the database, one is through mysqli, and the other is Connecting to the database through PDO and through mysqli can also be divided into two situations: mysqli (object-oriented), mysqli (process-oriented).
There are three ways:
1) PDO connects to mysql
2 ) mysqli (object-oriented) connects to the database
3) mysqli (process-oriented) connects to the database
(In fact, there is another connection method: using the MySQL extension. However, this extension is not recommended for use in 2012.)
You can first check whether your php has PDO installed through the phpinfo() command (I use php7, it is already installed by default)
If it is not installed, refer to the web page: http://php.net/manual/en/pdo.installation.php
Code example:
<?php $servername = "localhost"; $username = "root"; $password = "root"; try { $conn = new PDO("mysql:host=$servername;dbname=jtsys", $username, $password); echo "连接成功"; } catch(PDOException $e) { echo $e->getMessage(); } ?>
(Please pay attention to changes when using Database user name and password, as well as the selected database name (dbname)
You can first check yours through the phpinfo() command Whether mysqli has been installed in php (I use php7, it is already installed by default)
If not, please refer to the web page: http://php.net/manual/en/mysqli.installation.php
Code example:
<?php $servername = "localhost"; $username = "root"; $password = "root"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $dbname="jtsys"; mysqli_select_db($conn,$dbname); echo "连接成功"; ?>
Code example:
<?php $servername = "localhost"; $username = "root"; $password = "root"; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $dbname="jtsys"; mysqli_select_db($conn,$dbname); echo "连接成功"; ?>
1. How to close the connection:
PDO:
$conn = null;
MySQLi (object-oriented):
$conn->close();
MySQLi ( Process-oriented):
mysqli_close($conn);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Is there any difference between the ways php connects to mysql?. For more information, please follow other related articles on the PHP Chinese website!