消防车,PDO和Mysqli数据分析与梳理小结-anggame安博电竞_安博电竞网页版_安博电竞

好莱坞在线 292℃ 0

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

衔接方法

// PDO
$pdo = new PDO("mysql:host=localhost;dbname=database", 'usernam观阴e', 'password');

// m消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞ysqli面向进程
$mysqli = mysqli_connect('localhost','username','password','database');

// mysqli面向目标
$myprouncesqli = new m消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞ysqli('localhost','username','password','database');

对数据库的支撑方面

pdo多种支撑

代码体现

var_dump(PDO::getAvailableDriv消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞ers());

mysqli 单一

参数绑定

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

$pdo->prepare('
SELECT * FROM users
WHERE usern消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞ame = :username
AND email = :email
AND last_login > :last_login');

$pdo->execute($params);
  • mysqli方法
  • $query = $mysqli->prepare('
  • SELECT * FROM users
  • WHERE user消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞name = ?
  • AND email = ?
  • AND last_login > ?');
  • $query->bind_param('sss', 'test', $mail, time() - 3600);
  • $query->execute();

目标映射

假定咱们有一个类,是如消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞下这样

class User {
public $id;
public $first_name;
public $last_我国国家博物馆name;

public functio猪肚汤n info()
{
return '#'.$this->id.': '.$this->fi小白rst_name.' '.$this->last_name;
}
}

看看2者的方法

$query = "SEL焦晃ECT i消防车,PDO和Mysqli数据剖析与整理小结-anggame安博电竞_安博电竞网页版_安博电竞d, 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 $use厚道告知我是谁r->info()."\n";
}
}
// MySQLi, object oriented way
if ($男明星result = $mysqli->query($query)) {
while ($user = $result->fetch_object('User')) {
echo $u阿斯克码表ser->info()."\n";
}
}

安全方面

二者都可以避免sql注入

看下代码

// PDO, "m首都机场anual" escaping
$username = PDO::quote($_GET['username']);

$pdo小孩拉肚子怎么办->query("SELECT * FROM users WHERE username = $user春风雷诺name");

// mysqli, "manual" escaping
$username = mysqli_real_escape_string($_GET['username']);

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

预处理机制

// PDO, prepared statement
$pdo->prepare('SELECT * FROM users WHERE username 福娃= :username');
$pdo->execute(a南浔rray(':use海参的成效与效果rname' => $_GET['username']));

// mysqli, prepared statements
$query = $mysqli->prepare('SELECT * FROM users WHERE u美国气候sername = ?');
$query->bind_param('s', $_GET['username']);
$query->execute();

总结

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

————————————————骨加宽

原文链接:https://blog.csdn.net雨果奖/dzyweer/article/details/79751174