从官方给出的这份结果上来看,优先推荐msqli,其次是PDO 。而“民间”给出的结果很多是倾向于使用PDO,因为其不担有跨库的优点,更有读写速度快的特点。
1.PHP与Mysql扩展(本扩展自 PHP 5.5.0 起已废弃,并在将来会被移除),PHP原生的方式去连接数据库,是面向过程的
<?php $mysql_conf = array( 'host' => '127.0.0.1:3306', 'db' => 'test', 'db_user' => 'root', 'db_pwd' => 'root', ); $mysql_conn = @mysql_connect($mysql_conf['host'], $mysql_conf['db_user'], $mysql_conf['db_pwd']); if (!$mysql_conn) { die("could not connect to the database:\n" . mysql_error());//诊断连接错误 } mysql_query("set names 'utf8'");//编码转化 $select_db = mysql_select_db($mysql_conf['db']); if (!$select_db) { die("could not connect to the db:\n" . mysql_error()); } $sql = "select * from user;"; $res = mysql_query($sql); if (!$res) { die("could get the res:\n" . mysql_error()); } while ($row = mysql_fetch_assoc($res)) { print_r($row); } mysql_close($mysql_conn); ?>
2.PHP与Mysqli扩展,面向过程、对象
<?php $mysql_conf = array( 'host' => '127.0.0.1:3306', 'db' => 'test', 'db_user' => 'root', 'db_pwd' => 'joshua317', ); $mysqli = @new mysqli($mysql_conf['host'], $mysql_conf['db_user'], $mysql_conf['db_pwd']); if ($mysqli->connect_errno) { die("could not connect to the database:\n" . $mysqli->connect_error);//诊断连接错误 } $mysqli->query("set names 'utf8';");//编码转化 $select_db = $mysqli->select_db($mysql_conf['db']); if (!$select_db) { die("could not connect to the db:\n" . $mysqli->error); }$sql = "select uid from user where name = 'joshua';"; $res = $mysqli->query($sql); if (!$res) { die("sql error:\n" . $mysqli->error); } while ($row = $res->fetch_assoc()) { var_dump($row); } $res->free(); $mysqli->close(); ?>
3.PHP与PDO扩展,面向过程、对象
<?php $mysql_conf = array( 'host' => '127.0.0.1:3306', 'db' => 'test', 'db_user' => 'root', 'db_pwd' => 'joshua317', ); $pdo = new PDO("mysql:host=" . $mysql_conf['host'] . ";dbname=" . $mysql_conf['db'], $mysql_conf['db_user'], $mysql_conf['db_pwd']);//创建一个pdo对象 $pdo->exec("set names 'utf8'"); $sql = "select * from user where name = ?"; $stmt = $pdo->prepare($sql); $stmt->bindValue(1, 'joshua', PDO::PARAM_STR); $rs = $stmt->execute(); if ($rs) { // PDO::FETCH_ASSOC 关联数组形式 // PDO::FETCH_NUM 数字索引数组形式 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { var_dump($row); } } $pdo = null;//关闭连接 ?>
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP基于pdo操作数据库技巧总结》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》