平时常用框架自带的类来操作数据库,今天重温php的pdo的相关知识,记录如下。
PHP PDO链接MySql数据库
$db = new PDO('mysql:host=localhost;dbname=test','root','123456');
$db->exec('set names utf-8');
其中,localhost可以改写为ip地址。若为正式环境,建议写线上服务器的内网地址;root为数据库用户名,123456为密码。
假若建表如下
CREATE TABLE `news` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`ctime` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
查询
简单查询
$sql = "select * from news order by id desc";
$db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
或用占位符
$sql = "select * from news where id >= ? order by id desc";
$sth = $db->prepare($sql);
$sth->execute([1]);
print_r($sth->fetchAll(PDO::FETCH_ASSOC));
若数据量大,为减轻数据库压力,可以用fetch更换fetchAll。再遍历结果集获取查询后的关联数组。
$sql = "select * from news where id >= ? order by id desc";
$sth = $db->prepare($sql);
$result = [];
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
添加
$sql = "insert into news (title,ctime) values ('title1','2017-09-09 10:01:00')";
$sth = $db->prepare($sql);
$sth->execute();
或用占位符
$sql = "insert into news (title, ctime) values (?,?)";
$sth = $db->prepare($sql);
$sth->execute(['title1','2017-09-09 10:01:00']);
添加多条数据
如果想插入多条数据,不想写很多的? ,同时execute又不支持通过二维数组传参 [ ['title1','2017-09-09 10:01:00'], ['title2','2017-09-09 10:02:00'] ].我们可以采用参数绑定的方法(当然也可以拼接sql等),来添加多条数据。
$sql = 'insert into news (title,ctime) values (:title, :ctime)';
$sth = $db->prepare($sql);
$data = [
['title'=>'title1', 'ctime'=>'2017-09-09 10:01:00'],
['title' => 'title2', 'ctime' =>'2017-09-09 10:02:00']
];
try {
$db->beginTransaction();
foreach ($data as $item) {
$sth->bindValue(':title', $item['title']);
$sth->bindValue(':ctime', $item['ctime']);
$sth->execute();
}
$db->commit();
} catch (PDOException $e) {
$db->rollBack();
}
修改
$sql = "update news set title = 'news01' where id = 1";
$sth = $db->prepare($sql);
$sth->execute();
或
$sql = "update news set title = 'news01' where id = ?";
$sth = $db->prepare($sql);
$sth->execute([1]);
删除
$sql = "delete from news where id = 2";
$sth = $db->prepare($sql);
$sth->execute();
或
$sql = "delete from news where id = ?";
$sth = $db->prepare($sql);
$sth->execute([1]);