PHP MySQL 讀取資料
從MySQL 資料庫讀取資料
SELECT 語句用於從資料表中讀取資料:
# SELECT column_name(s) FROM table_name
如需學習更多關於SQL 的知識,請造訪我們的 SQL 教學課程。
以下實例中我們從表MyGuests 讀取了id, firstname 和lastname 欄位的資料並顯示在頁面上:
實例(MySQLi - 物件導向)
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"]; } } else { echo "0 个结果"; } $conn->close(); ?>
下列實例讀取了MyGuests 資料表的所有記錄並顯示在HTML 表格中:
實例(PDO)
<?php echo "<table style='border: solid 1px black;'>"; echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th><th>Email</th><th>Reg date</th></tr>"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>"; } function beginChildren() { echo "<tr>"; } function endChildren() { echo "</tr>" . "\n"; } } $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT * FROM MyGuests"); $stmt->execute(); // 设置结果集为关联数组 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } $dsn = null; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo "</table>"; ?>
##下一節