【转载】http://www.cnblogs.com/52fhy/p/5352304.html
本文将举详细例子向大家展示PHP是如何使用MySQL原生API、MySQLi面向过程、MySQLi面向对象、PDO操作MySQL数据库的。
为了后面的测试,先建立数据库表test。包含表名user,score。
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL DEFAULT '',
`gender` tinyint(1) NOT NULL DEFAULT '1',
`age` int(11) NOT NULL DEFAULT '0',
`flag` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
insert into `user`(`id`,`name`,`gender`,`age`,`flag`) values (1,'allen',1,20,1),(2,'alice',2,18,1),(3,'bob',1,21,1),(4,'dave',1,25,1),(5,'eve',2,20,1),(6,'joy',1,21,1),(7,'june',1,23,1),(8,'linda',2,22,1),(9,'lisa',2,22,1),(10,'liz',2,23,1);
CREATE TABLE `score` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL DEFAULT '0',
`score` int(11) NOT NULL DEFAULT '0',
`flag` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
/*Data for the table `score` */
insert into `score`(`id`,`uid`,`score`,`flag`) values (1,1,89,1),(2,2,98,1),(3,3,78,1),(4,4,88,1),(5,5,99,1),(6,6,89,1),(7,7,90,1),(8,8,93,1),(9,9,95,1),(10,10,99,1);
使用原生 MySQL API
MySQL API 大部分扩展自 PHP 5.5.0 起已废弃,并在将来会被移除。应使用 MySQLi或 PDO_MySQL 扩展来替换之。
配置并连接数据库
//配置
$db = array(
'dsn' => 'mysql:host=localhost;dbname=test',
'host' => 'localhost',
'dbname' => 'test',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
);
//建立连接
$link = mysql_connect($db['host'], $db['username'], $db['password']) or die( 'Could not connect: ' . mysql_error ());
//选择数据库
mysql_select_db($db['dbname'], $link) or die ( 'Can\'t use foo : ' . mysql_error ($link));
mysql_set_charset($db['charset'], $link);
查询并遍历数据:
//普通查询,返回资源
//mysql_query() 仅对 SELECT,SHOW,DESCRIBE