0717-7821348
新闻中心

行业新闻

您现在的位置: 首页 > 新闻中心 > 行业新闻
PDO和Mysqli比照剖析与概括总结
2019-12-14 02:07:04

php操作mysql数据库,咱们都知道有三种驱动,mysql mysqli pdo,其间mysql在php7之后被废除了。不是本文要点。咱现在来剖析一下mysqli和PDO的差异,下面一张表用来阐明他们的差异:

衔接方法

// PDO
$pdo = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');

// mysqli面向进程
$mysqli = mysqli_connect('localhost','username','password','database');

// mysqli面向目标
$mysqli = new mysqli('localhost','username','password','database');

对数据PDO和Mysqli比照剖析与概括总结库的支撑方面

pdo多种支撑

代码体现

var_dump(PDO::getAvailableDrivers());

mysqli 单一

参数绑定

  • POD方法
$params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);

$pdo->prepare('
SELECT * FROM users
WHERE username = :username
AND email = :email
AND last_login > :last_loginPDO和Mysqli比照剖析与概括总结');

$pdo->execute($params);
  • mysqli方法
  • $query = $mysqli->prepare('
  • SELECT * FROM users
  • WHERE usernPDO和Mysqli比照剖析与概括总结ame = ?
  • AND email = ?
  • AND last_login > ?');
  • $quPDO和Mysqli比照剖析与概括总结ery->bind_param('sss', 'test', $mail, time() - 3600);
  • $query->execute();

目标映射

假定咱们有一个类,是如下这样

class User {
public $id;
public $first_name;
public $last_name;

public function info()
{
return '#'.$this->id.': '.$this->first_name.' '.$this->last_name;
}
}

看看2者的方法

$query = "SELECT id, first_name, last_name FROM users";

// PDO
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_CLASS, 'User');

while ($user = $result->fetch()) {
echo $user->info()."\n";
}
// MySQLI, procedural way
if ($result = mysqli_query($mysqli, $query)) {
while ($user = mysqli_fetch_object($result, 'User')) {
echo $user->info()."\n";
}
}
// MySQLi, object oriented way
if ($result = $mysqli->query($query)) {
while ($user = $result->fetch_object('User')) {
echo $user->info()."\n";
}
}

安全方面

二者都可以避免sql注入

看下代码

// PDO, "manual" escaping
$username = PDO::quote($_GET['username']);

$pdo->query("SELECT * FROM users WHERE username = $username");

// mysqli, "manual" escaping
$username = mysqli_real_escape_string($_GET['usernPDO和Mysqli比照剖析与概括总结ame']);

$mysqli->query("SELECT * FROM users WHERE username = '$username'");

预处理机制

// PDO, prepared statement
$pdo->prepare('SELECT * FROM users WHERE username = :username');
$pdo->execute(array(':username' => $_GET['username']));

// mysqli, prepared statements
$query = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
$query->bind_param('s', $_GET['username']);
$query->exPDO和Mysqli比照剖析与概括总结ecute();

总结

引荐咱们用pdo,由于pdo的强壮之处是清楚明了的,支撑多种数据库,还有参数绑定是特征。

————————————————

原文链接:https://blog.csdn.net/dzyweer/article/detail红烧草鱼s/79751174