PHP MySQL 讀取資料

來源:互聯網
上載者:User

標籤:

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("Connection failed: " . $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 results";
}
$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>";
?>

PHP MySQL 讀取資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.