php ,MySQL操作的兩種方式

來源:互聯網
上載者:User

標籤:

本文省略php對MySQL的面向過程的操作方式,介紹最常用的,物件導向的操作方式和PDO方式

物件導向的操作方式:

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// 建立串連
$conn = new mysqli($servername, $username, $password);

// 確定資料庫,建立串連
//$conn = new mysqli($servername, $username, $password, $dbname);
// 檢測串連
if ($conn->connect_error) {
    die("串連失敗: " . $conn->connect_error);
}

// 建立資料庫
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "資料庫建立成功";
} else {
    echo "Error creating database: " . $conn->error;
}

//選擇資料庫

mysql_select_db( ‘MyDB‘ );

// 使用 sql 建立資料表
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "建立資料表錯誤: " . $conn->error;
}

//插入資料
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John‘, ‘Doe‘, ‘[email protected]‘)";

if ($conn->query($sql) === TRUE) {
    echo "新記錄插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
//插入多條資料
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John‘, ‘Doe‘, ‘[email protected]‘);";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Mary‘, ‘Moe‘, ‘[email protected]‘);";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Julie‘, ‘Dooley‘, ‘[email protected]‘)";

if ($conn->multi_query($sql) === TRUE) {
    echo "新記錄插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


// 預先處理及綁定
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// 設定參數並執行
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();

echo "新記錄插入成功";

$stmt->close();


//讀取資料
$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();
?>

 

使用pdo方式

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);

    // 設定 PDO 錯誤模式為異常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "CREATE DATABASE myDBPDO";

    // 使用 exec() ,因為沒有結果返回
    $conn->exec($sql);

    echo "資料庫建立成功<br>";      // 使用 sql 建立資料表
   $sql = "CREATE TABLE MyGuests (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
    )";
    // 使用 exec() ,沒有結果返回
    $conn->exec($sql);
    echo "資料表 MyGuests 建立成功";//插入資料    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
   VALUES (‘John‘, ‘Doe‘, ‘[email protected]‘)";
    // 使用 exec() ,沒有結果返回
    $conn->exec($sql);
    echo "新記錄插入成功";//插入多條資料    // 開始事務
    $conn->beginTransaction();
    // SQL 陳述式
    $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
    VALUES (‘John‘, ‘Doe‘, ‘[email protected]‘)");
    $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
    VALUES (‘Mary‘, ‘Moe‘, ‘[email protected]‘)");
    $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
    VALUES (‘Julie‘, ‘Dooley‘, ‘[email protected]‘)");

    // 提交事務
    $conn->commit();
    echo "新記錄插入成功";   // 預先處理 SQL 並綁定參數
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
    VALUES (:firstname, :lastname, :email)");
    $stmt->bindParam(‘:firstname‘, $firstname);
    $stmt->bindParam(‘:lastname‘, $lastname);
    $stmt->bindParam(‘:email‘, $email);

    // 插入行
    $firstname = "John";
    $lastname = "Doe";
    $email = "[email protected]";
    $stmt->execute();

    // 插入其他行
    $firstname = "Mary";
    $lastname = "Moe";
    $email = "[email protected]";
    $stmt->execute();

    // 插入其他行
    $firstname = "Julie";
    $lastname = "Dooley";
    $email = "[email protected]";
    $stmt->execute();

    echo "新記錄插入成功"; //查詢資料  $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;
    }
    $stmt = null;
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

 

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.