PHP PDO對mysql的常規操做

平時經常使用框架自帶的類來操做數據庫,今天重溫php的pdo的相關知識,記錄以下。php

PHP PDO連接MySql數據庫

$db = new PDO('mysql:host=localhost;dbname=test','root','123456');
$db->exec('set names utf-8');

其中,localhost能夠改寫爲ip地址。若爲正式環境,建議寫線上服務器的內網地址;root爲數據庫用戶名,123456爲密碼。mysql

倘若建表以下sql

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']);

添加多條數據fetch

若是想插入多條數據,不想寫不少的? ,同時execute又不支持經過二維數組傳參 [ ['title1','2017-09-09 10:01:00'], ['title2','2017-09-09 10:02:00'] ].咱們能夠採用參數綁定的方法(固然也能夠拼接sql等),來添加多條數據。spa

$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();

code

$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]);
相關文章
相關標籤/搜索