PDO(PHP數據對象) 是一個輕量級的、具有兼容接口的PHP數據連接拓展,是一個PHP官方的PECL庫,隨PHP 5.1發布,需要PHP 5的面向對象支持,因而在更早的版本上無法使用。它所提供的數據接入抽象層,具有與具體數據庫類型無關的優勢,為它所支持的數據庫提供統一的操作接口。目前支持多種數據庫等。由於PDO是在底層實現的統一的數據庫操作接口,因而利用它能夠實現更高級的數據庫操作,比如存儲過程的調度等。
創建數據庫配置文件config.php
<?php define('DB_HOST','localhost');//常量,主機名
define('DB_USER','root');//連接數據庫的用戶名
define('DB_PWD','root');//連接數據庫密碼
define('DB_NAME','book');//數據庫名稱
define('DB_PORT','3306');//端口號
define('DB_TYPE','mysql');//數據庫的類型
define('DB_CHARSET','utf8');//數據庫的編碼格式
define('DB_DSN',DB_TYPE.":host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET);//定義PDO的DSN
?>
創建index.php文件,用於連接數據庫,執行查詢語句,並引入config.php文件
<?php require "config.php"; try{ //連接數據庫,選擇數據庫
$pdo = new PDO(DB_DSN,DB_USER,DB_PWD); } catch (PDOException $e){ //輸出異常信息
echo $e->getMessage(); } $query = "select * from books where id=?";//sql語句
$sth = $pdo->prepare($query);//准備執行
$sth->execute(array(1));//執行查詢語句,並返回結果集 //var_dump($sth->fetchColumn(1)); //var_dump($sth->fetchColumn(1)); //$res = $sth->fetch(PDO::FETCH_OBJ);
include("lists_02.html");
創建list.html文件,顯示查詢信息。
<!DOCTYPE html>
<html lang="en" class="is-centered is-bold">
<head>
<meta charset="UTF-8">
<title>連接數據庫</title>
<link href="css/bootstrap.css" rel="stylesheet">
<style> #name,#id{ width: 200px; margin-top: 10px;
}
</style>
</head>
<body>
<div class="container" style="padding-top: 20px">
<div class="col-sm-offset-2 col-sm-8">
<div class="panel panel-default">
<div class="panel-heading"> 圖書列表 </div>
<div class="panel-body">
<table class="table table-striped task-table">
<thead>
<tr>
<th>ID</th>
<th>書姓</th>
<th>作者</th>
<th>價格</th>
<th>出版日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!--$getData數組的值也是數組-->
<?php while ($res = $sth->fetch(PDO::FETCH_OBJ)){ ?>
<tr>
<td class="table-text">
<?php echo $res->id ?>
</td>
<td class="table-text">
<?php echo $res->name ?>
</td>
<td class="table-text">
<?php echo $res->author ?>
</td>
<td class="table-text">
<?php echo $res->price ?>
</td>
<td class="table-text">
<?php echo $res->publishDate ?>
</td>
<td class="table-text">
<button type="button" class="btn btn-primary">編輯</button>
<button type="button" class="btn btn-danger">刪除</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</body>
</html>