本篇主要就是講基本的用PDO從資料庫中讀取資料至網頁來。
開發環境:自家的單機伺服器,使用XAMPP、PHP 5.6.12版、MySQL 5.6.26、Apache 2.4.16
要連的資料庫名稱 xanxus
裡面長這樣 SQL碼:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; CREATE TABLE IF NOT EXISTS `member_table` ( `id` int(20) NOT NULL, `lv` int(20) NOT NULL, `username` char(30) COLLATE utf8_unicode_ci NOT NULL, `password` char(30) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=MyISAM AUTO_INCREMENT=69 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `member_table` (`id`, `lv`, `username`, `password`) VALUES (41, 1, 'a1', '123'), (42, 2, 'a2', '123'), (43, 3, 'a3', '123'), (44, 4, 'a4', '123'); ALTER TABLE `member_table` ADD PRIMARY KEY (`id`); ALTER TABLE `member_table` MODIFY `id` int(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=69;
連線檔 PDO_Connect.php
<?php @header('Content-Type: text/html; charset=utf-8'); $hostname = 'localhost'; $username = 'root'; $password = 'root'; $db_name="xanxus"; $db=new PDO("mysql:host=".$hostname."; dbname=".$db_name, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); //PDO::MYSQL_ATTR_INIT_COMMAND 設定編碼 //echo '連線成功'; $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); //錯誤訊息提醒 ?>
PDO_PHP_Inquiry.php
<?php include("PDO_Connect.php");//PDO連線檔 $id = 1; $sql="SELECT * FROM `member_table`"; $result=$db->query($sql); //PDO::FETCH_ASSOC 指定資料庫欄位字串,foreach寫法 $list = $result->fetchAll(PDO::FETCH_ASSOC); echo "<table border=1 class='table table-striped table-bordered table-hover table-condensed'>"; $fieldArray = array('序號','等級','使用者名稱','密碼');//儲存欄位名稱陣列 $lengthfield = count($fieldArray); echo "<thead>"; echo "<tr class=\"success\">"; for($i=0;$i<$lengthfield;$i++){ echo "<th>{$fieldArray[$i]}</th>"; } echo "</tr>"; echo "</thead>"; foreach ($list as $row ) { echo "<tr>"; echo "<td>".$id++."</td>"; echo "<td>".$row["lv"]."</td>"; echo "<td>".$row["username"]."</td>"; echo "<td>".$row["password"]."</td>"; } echo "</tr>"; echo "</table>"; ?>
結果:
沒有留言:
張貼留言