Hướng dẫn what is advantage of pdo or mysqli? - lợi thế của pdo hoặc mysqli là gì?

Introduction

Long gone are the days of using the

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
5 extension, as its methods have been deprecated since PHP 5.5 and removed as of PHP 7. Alas, the internet is still plagued with a ton of old tutorials that beginners will simply copy/paste and use on a shared hosting platform with an older PHP version, thus continuing its legacy.

Show

If you are using MySQL or MariaDB in PHP, then you have the ability to choose either MySQLi or PDO. The former is simply an improved version with procedural and OOP support and added prepared statements, while the latter is an abstraction layer that allows you to use a unified API for all 12 database drivers it supports. Though it should be mentioned that MySQL is undoubtedly the most popular database to use in the PHP world anyway.

In theory, one might assume the discussion should be over. We don't need a vendor-specific API for every type of database that exists, as it's so much simpler to use just one. While there's certainly a lot of truth to this, the problem is that

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
6 simply doesn't have all of the newest and most advanced features MySQLi does. I honestly don't understand why this is the case, as it would completely eliminate any reason to use the vendor-specific API. That said, I'd imagine that most people don't need these extra features, but there are definitely some who do.

For anyone who's interested, here's a full writeup of PDO and MySQLi.

PDO Advantages

MySQLi has quite a few aspects to play catchup with PDO. It needs to adds features like:

  1. Useful fetch modes
  2. Allow to pass variables and values directly into execute
  3. Ability to auto-detect variable types (What actually happens is that everything is treated as a string when sent to the sever, but is converted to the correct type. This works 100% of the time with native prepared statements but doesn't work with certain edge cases, such as LIKE with emulation mode.)
  4. Provides an option to have automatically buffered results with prepared statements
  5. Named parameters (though useless with emulation mode turned off in PDO, as you can only use the same name once)

As you can see, there are quite a few things MySQLi should learn from PDO if it wants to stay relevant.

If it does, then there should really be no difference at all. People always talk about how you'd have to learn a whole new extension, yet they're actually already nearly identical for the most part. For this article, I'll be using native prepared statements, but emulated ones are perfectly acceptable as well. Here's a short writeup on the differences between the two.

MySQLi Advantages

PDO is also missing some features, albeit far less important ones for most users, such as:

  1. Asynchronous queries
  2. Ability to get more info on affected rows, like updating a row with the same values (can be done in PDO as a constructor setting you can't change it later)
  3. Proper database closing method
  4. Multiple queries at once (though it can if emulation mode is turned on in PDO)
  5. Automatic cleanup with persistent connections

So Which Should I Use?

My opinion is that PDO should be used by default, especially beginners, due to its versatility, general predictability and useful fetch modes. However, MySQLi would be a better choice for advanced users who want the newest, MySQL-specific functionality.

It's somewhat ironic that more experienced PHP developers tend think PDO is the only acceptable option 100% of the time, while beginners tend to use MySQLi. This is absolutely nutty from both ends. Of course most developers don't really need the extra advanced features MySQLi offers, but it certainly could be extremely useful for some, as previously mentioned.

It's especially curious that novices are scared to try something "new" and switch to PDO, while a lot of advanced users recite the good ole "ease of switching from database driver" argument as PDO's advantage. Anyone who believes the myth that you can easily switch among databases in PDO seamlessly has obviously never attempted to do so. Each driver is different, and a switch from Microsoft SQL Server to MySQL will certainly not be automated. First of all let's make one thing clear, the syntax is very similar — almost identical, and I will present that in examples. PDO is also not some abstraction layer over MySQLi, but rather over PDO_MYSQL.

If PDO does end up keeping up with all of the latest or distinct MySQL functionality, then I could see why MySQLi should go away; I'd even encourage it, if it ends up being the case. Though PDO does have several driver-specific features, it doesn't have all nor keep up with the latest. This is precisely why I don't think MySQLi and PDO aren't necessarily competitors, but rather two powerful libraries with completely different focuses for now. Obviously PDO should be more widely used, however. But as said before, the difference is pretty much negligible as is anyway. As mentioned several times earlier, MySQLi's survival relies on it catching up to PDO, along with PDO primarily sticking with features that are used among most of the DB drivers it supports.

Sự khác biệt về mã

Như đã nêu trước đó, cả PDO và MySQLI đều cực kỳ giống nhau, nhưng có sự khác biệt nhỏ về cú pháp. MySQLI tuân theo quy ước Php Snake_case trường học cũ, trong khi PDO sử dụng Camelcase. Ngoài ra, các phương thức của MySQLI được sử dụng làm thuộc tính đối tượng, trong khi PDO sử dụng cú pháp truyền thống cho các chức năng.

Tôi sẽ không bao giờ hiểu tại sao cả PDO và MySQLI đều phức tạp bằng cách buộc bạn sử dụng hai phương pháp riêng biệt để sử dụng câu lệnh đã chuẩn bị. May mắn thay, PDO đã loại bỏ nhu cầu sử dụng chức năng ràng buộc chuyên dụng - mặc dù tôi không chắc tại sao điều tương tự không được thực hiện cho

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
7. MySQLI và PDO không chuẩn bị thực sự không quá tệ, và đó thực sự là việc thực hiện không may các tuyên bố đã chuẩn bị khiến chúng có vẻ dài dòng. Chẳng hạn, trong API PostgreSQL dành riêng cho nhà cung cấp, bạn có thể làm điều đó như thế này. Dưới đây là một ví dụ về cách bạn thực hiện truy vấn "không chuẩn bị" để lấy mảng kết hợp với MySQLI và PDO, để tham khảo.

$arr = $mysqli->query("SELECT * FROM myTable")->fetch_all(MYSQLI_ASSOC);
$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);

Trong thực tế, tuyến đường tốt nhất là sử dụng trình bao bọc, trình tạo truy vấn hoặc ORM. Tôi có một trình bao bọc Mysqli khá thô sơ mà bạn có thể thích. Mặc dù PDO là một bước đi đúng hướng, vì bạn có thể liên kết các giá trị trực tiếp vào thực thi, nhưng nó vẫn không lý tưởng. Trong lớp tôi đã thực hiện, bạn có thể xâu chuỗi tất cả các cuộc gọi của mình, trong khi chuyển các giá trị để liên kết dưới dạng đối số tham số. Kiểm tra những gì bạn có thể làm.

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');

Bây giờ bạn có toàn bộ một mảng kết hợp được lưu trữ trong biến một cách ngắn gọn hơn nhiều. Thật lạ khi cả PDO và MySQLI không làm như vậy.

Đối với phần còn lại của hướng dẫn, chúng tôi sẽ sử dụng các câu lệnh đã chuẩn bị, vì không có lý do chính đáng để không sử dụng chúng để bảo vệ tiêm SQL, trừ khi bạn sử dụng một tính năng như Async, hiện không hỗ trợ chúng. Nếu không, bạn sẽ cần phải định dạng thủ công các truy vấn của mình.

Tạo kết nối cơ sở dữ liệu mới

PDO

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}

Mysqli

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}

Chèn, cập nhật, xóa

PDO

$stmt = $pdo->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->execute([$_POST['name'], 29]);
$stmt = null;

Mysqli

$stmt = $mysqli->prepare("UPDATE myTable SET name = ? WHERE id = ?");
$stmt->bind_param("si", $_POST['name'], $_SESSION['id']);
$stmt->execute();
$stmt->close();

Chèn, cập nhật, xóa

Cần lưu ý rằng với PDO, bạn có thể chuỗi mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try { $mysqli = new mysqli("localhost", "username", "password", "databaseName"); $mysqli->set_charset("utf8mb4"); } catch(Exception $e) { error_log($e->getMessage()); exit('Error connecting to database'); //Should be a message a typical user could understand } 8 và mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try { $mysqli = new mysqli("localhost", "username", "password", "databaseName"); $mysqli->set_charset("utf8mb4"); } catch(Exception $e) { error_log($e->getMessage()); exit('Error connecting to database'); //Should be a message a typical user could understand } 7, mặc dù bạn sẽ không nhận được các hàng bị ảnh hưởng, vì vậy tôi không thể thấy điều đó hữu ích.

PDO

$stmt->rowCount();

Mysqli

$stmt->affected_rows;

Chèn, cập nhật, xóa

Cần lưu ý rằng với PDO, bạn có thể chuỗi

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
8 và
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
7, mặc dù bạn sẽ không nhận được các hàng bị ảnh hưởng, vì vậy tôi không thể thấy điều đó hữu ích.

PDO

$pdo->lastInsertId();

Mysqli

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
0

Chèn, cập nhật, xóa

PDO

Mysqli

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
1

Mysqli

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
2

Chèn, cập nhật, xóa

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
3

Cần lưu ý rằng với PDO, bạn có thể chuỗi

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
8 và
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
7, mặc dù bạn sẽ không nhận được các hàng bị ảnh hưởng, vì vậy tôi không thể thấy điều đó hữu ích.

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
4

Nhận số lượng hàng bị ảnh hưởng

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
5

Nhận khóa chính mới nhất được chèn

Lưu ý, làm thế nào cả hai sử dụng biến kết nối, thay vì $stmt = $pdo->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)"); $stmt->execute([$_POST['name'], 29]); $stmt = null; 0.

PDO

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
6

Mysqli

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
7

Chèn, cập nhật, xóa

PDO

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
8

Mysqli

$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
9

Chèn, cập nhật, xóa

PDO

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
0

Mysqli

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
1

Chèn, cập nhật, xóa

PDO

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
2

Mysqli

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
3

Chèn, cập nhật, xóa

Cần lưu ý rằng với PDO, bạn có thể chuỗi mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try { $mysqli = new mysqli("localhost", "username", "password", "databaseName"); $mysqli->set_charset("utf8mb4"); } catch(Exception $e) { error_log($e->getMessage()); exit('Error connecting to database'); //Should be a message a typical user could understand } 8 và mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try { $mysqli = new mysqli("localhost", "username", "password", "databaseName"); $mysqli->set_charset("utf8mb4"); } catch(Exception $e) { error_log($e->getMessage()); exit('Error connecting to database'); //Should be a message a typical user could understand } 7, mặc dù bạn sẽ không nhận được các hàng bị ảnh hưởng, vì vậy tôi không thể thấy điều đó hữu ích.

PDO

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
4

Mysqli

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
5

Chèn, cập nhật, xóa

Cần lưu ý rằng với PDO, bạn có thể chuỗi

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
8 và
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
7, mặc dù bạn sẽ không nhận được các hàng bị ảnh hưởng, vì vậy tôi không thể thấy điều đó hữu ích.

Nhận số lượng hàng bị ảnh hưởng

PDO

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
6

Mysqli

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
7

Output:

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
8

Chèn, cập nhật, xóa

PDO

$arr = $mysqli->query("SELECT * FROM myTable WHERE id > ?", [12])->fetchAll('assoc');
9

Mysqli

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
0

Output:

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
1

Chèn, cập nhật, xóa

PDO

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
2

Mysqli

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
3

Output:

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
4

Chèn, cập nhật, xóa

PDO

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
5

Mysqli

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
6

Output:

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
7

Chèn, cập nhật, xóa

PDO

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
8

Mysqli

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('Something weird happened'); //something a user can understand
}
9

Chèn, cập nhật, xóa

PDO

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
0

Mysqli

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
1

Chèn, cập nhật, xóa

PDO

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
2

Mysqli

Mysqli

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
3

Chèn, cập nhật, xóa

Các tham số được đặt tên

Đây là một tính năng chỉ có PDO, nhưng nó chỉ hữu ích nếu chế độ mô phỏng bị tắt. Nếu không, bạn chỉ có thể sử dụng cùng một biến một lần. Cũng cần lưu ý rằng không bắt buộc đại tràng hàng đầu, nhưng điều này không được ghi nhận ở bất cứ đâu. Nó có thể cuối cùng sẽ dù sao, nhưng bạn không bao giờ biết, tôi cho rằng. Bạn cũng không thể trộn

$stmt = $pdo->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->execute([$_POST['name'], 29]);
$stmt = null;
9 người giữ chỗ với những người được đặt tên; Nó là cái này hay cái kia.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $mysqli = new mysqli("localhost", "username", "password", "databaseName");
  $mysqli->set_charset("utf8mb4");
} catch(Exception $e) {
  error_log($e->getMessage());
  exit('Error connecting to database'); //Should be a message a typical user could understand
}
4

PDO có nhanh hơn mysqli không?

PDO cũng hỗ trợ các truy vấn phía máy khách. Điều này có nghĩa là khi nó chuẩn bị một truy vấn, nó không phải giao tiếp với máy chủ. Vì MySQLI sử dụng các câu lệnh được chuẩn bị gốc, nên việc sử dụng mysqli_real_escape_string thực sự sẽ nhanh hơn thay vì sử dụng các câu lệnh đã chuẩn bị, trong khi nó vẫn là một giải pháp an toàn.it will may actually be faster to use mysqli_real_escape_string instead of using prepared statements, while it is still a secure solution.

Ưu điểm của PDO là gì?

Ưu điểm của PDO PDO cho phép chuyển đổi tương đối liền mạch giữa các cơ sở dữ liệu và nền tảng khác nhau, có thể dễ dàng thực hiện bằng cách thay đổi chuỗi kết nối. Nó không hỗ trợ cú pháp cụ thể của cơ sở dữ liệu. Tiện ích mở rộng PDO có thể truy cập bất kỳ cơ sở dữ liệu nào được viết cho trình điều khiển PDO.allows comparatively seamless switching between different databases and platforms, which can be easily done by changing the connection string. It does not support database-specific syntaxes. The PDO extension can access any database which is written for PDO driver.

Tôi nên học PDO hay mysqli?

Tuy nhiên, MySQLI sẽ là lựa chọn tốt hơn cho những người dùng nâng cao muốn chức năng mới nhất, cụ thể của MySQL.Thật là mỉa mai khi các nhà phát triển PHP có kinh nghiệm hơn có xu hướng nghĩ rằng PDO là lựa chọn duy nhất có thể chấp nhận được 100% thời gian, trong khi người mới bắt đầu có xu hướng sử dụng MySQLI.Đây là hoàn toàn hạt dẻ từ cả hai đầu.

PDO có an toàn hơn mysqli không?

PDO an toàn hơn so với hai tùy chọn đầu tiên và nó cũng nhanh hơn so với thủ tục MySQLI và hướng đối tượng MySQLI.PDO là lớp truy cập cơ sở dữ liệu cung cấp giao diện nhanh và nhất quán để truy cập và quản lý cơ sở dữ liệu trong các ứng dụng PHP. and it is also faster in comparison with MySQLi procedural and MySQLi object-oriented. PDO is a database access layer that provides a fast and consistent interface for accessing and managing databases in PHP applications.