PHP CRUD 操作初學者指南

王林
發布: 2024-07-17 12:41:23
原創
1001 人瀏覽過

介紹

PHP 是一種靈活且廣泛使用的伺服器端腳本語言,為我們今天看到的許多動態和互動式網頁提供支援。作為一個初學者,我發現學習 PHP 的旅程既充滿挑戰又充滿收穫。在這篇文章中,我們將在我上一篇文章中介紹的基礎知識的基礎上,探索 PHP 中更高級的主題。

如果您還沒有閱讀我的第一篇文章《PHP 入門:初學者指南》,我強烈建議您查看一下。它涵蓋了 PHP 的基礎知識,包括設定開發環境、理解基本語法以及使用變數和資料類型。

隨著我們深入研究 PHP,我歡迎任何回饋、建議或更正。您的評論不僅幫助我進步,也為所有讀者創造了一個協作學習的環境。讓我們一起繼續我們的 PHP 之旅!

設定 MySQL 資料庫

在開始編碼之前,我們需要設定一個 MySQL 資料庫。如果您安裝了 XAMPP,那麼您已經成功了一半!

在 XAMPP 中設定 MySQL

  1. 開啟 XAMPP 控制面板:啟動 XAMPP 控制面板並啟動「Apache」和「MySQL」服務。

  2. 開啟 XAMPP 控制面板:啟動 XAMPP 控制面板並啟動「Apache」和「MySQL」服務。

  3. 建立資料庫:

  • 點選左側邊欄的「新建」按鈕。

  • 輸入資料庫名稱,然後按一下「建立」。

還有另一個選擇,就是透過編寫 CREATE DATABASE database_name 來建立資料庫; SQL 腳本中的命令,然後按一下 Go 命令。

這些步驟如下圖所示。

Start the PHP and MySQL server with XAMPP

Open MySQL in XAMPP

建立資料庫的第一個選項:
Create new database

在 SQL 腳本上使用 MySQL 指令建立資料庫:
Create new database by using MySQL command

使用 phpMyAdmin 建立表

  1. 選擇您的資料庫:點選您剛剛建立的資料庫。

  2. 建立表格:

  • 輸入表的名稱(例如,使用者)。

  • 指定列數並按一下「開始」。

  • 定義欄位(例如,id、姓名、電子郵件、年齡)。

或透過在 SQL 腳本中使用 MySQL 指令

CREATE TABLE users (
    id INT(11) PRIMARY KEY AUTO_INCREMENT NOT NULL, 
    name VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL UNIQUE,
    age INT(3) NOT NULL
)
登入後複製


然後點擊開始。

將 PHP 連接到 MySQL

使用 'mysqli' 連接到 MySQL

更新了下面的程式碼

<!-- Opening PHP tag to write PHP code -->
<?php

// Specifies the hostname of the MySQL server.
$servername = "localhost";

// The MySQL username. "root" is the default administrative username for MySQL.
$username = "root";

// The MySQL password for the specified user. It is empty ("") by default for the root user in many local development environments.
$password = "";

// The name of the database you want to connect to.
$dbname = "php_project";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    // Log the error and display a generic message to the user
    error_log("Connection failed: " . mysqli_connect_error());
    die("Connection failed. Please try again later.");
}

// If the connection is successful, display or log a success message
echo "Connected successfully";

// Close the connection (optional, as it will close when the script ends)
mysqli_close($conn);

?>

登入後複製

執行CRUD操作

在 Web 開發環境中執行 CRUD 操作是指可以對資料庫中儲存的資料執行的基本操作:建立、讀取、更新和刪除。這些操作對於建立使用者可以與資料互動的動態和互動式 Web 應用程式至關重要。 CRUD 操作是 Web 應用程式中資料庫互動的支柱。 PHP 允許您透過定義包含 SQL 程式碼的變數並使用 PHP 的資料庫互動庫(如 MySQLi

執行它們)來輕鬆執行這些操作

建立:插入數據

更新了程式碼 ↓

<?php
// Set a value for each variable. Variables type of values should be same as set in database
$name = "person1";
$email = "person1@example.com";
$age = 25;

// Prepare the SQL statement
$stmt = mysqli_prepare($conn, "INSERT INTO users (name, email, age) VALUES ($name, $email, $age)");

// Bind parameters to the prepared statement
mysqli_stmt_bind_param($stmt, "ssi", $name, $email, $age);

// Execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
    echo "New record created successfully </br>";
} else {
    // Log the error for debugging purposes
    error_log("Error: " . mysqli_stmt_error($stmt));

    // Display a generic error message to the user
    echo "An error occurred while creating the record. Please try again later.";
}

// Close the prepared statement
mysqli_stmt_close($stmt);
登入後複製

閱讀:取得數據

讀取操作用於從資料庫中取得資料。這通常是使用 SQL 中的 SELECT 語句來完成的。以下是如何在 PHP 中執行讀取操作的逐步程式碼和說明:

// Create an SQL query
$sql = "SELECT id, name, email, age FROM users";
$result = mysqli_query($conn, $sql);

// Check if there are any results
if (mysqli_num_rows($result) > 0) {
    // Fetch and output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. " - Age: " . $row["age"]. "<br>";
    }
} else {
    echo "0 results";
}
登入後複製

更新:修改數據

您是否曾經需要修改資料庫中的現有資料?你是如何做到的?
PHP 中的更新操作用於修改 MySQL 資料庫中的現有記錄。這對於維護應用程式中準確且最新的數據至關重要。例如,如果使用者的資訊發生變化,例如他們的電子郵件地址或年齡,您將使用更新操作在資料庫中反映這些變更。

更新了程式碼

<?php
// Assuming you already have a connection established in $conn

$newAge = 32;
$email = 'person1@example.com';

// Prepare an SQL statement
$stmt = mysqli_prepare($conn, "UPDATE users SET age=$newAge WHERE email=$email");

if ($stmt) {
    // Bind parameters to the prepared statement
    mysqli_stmt_bind_param($stmt, "is", $newAge, $email);

    // Execute the prepared statement
    if (mysqli_stmt_execute($stmt)) {
        echo "Record updated successfully";
    } else {
        // Log the error internally, do not display it to the user
        error_log("Error executing statement: " . mysqli_stmt_error($stmt));
        echo "An error occurred while updating the record. Please try again later.";
    }

    // Close the statement
    mysqli_stmt_close($stmt);
} else {
    // Log the error internally, do not display it to the user
    error_log("Error preparing statement: " . mysqli_error($conn));
    echo "An error occurred. Please try again later.";
}

// Close the connection
mysqli_close($conn);
?>

登入後複製

根據上面編寫的程式碼,如果更新過程順利,我們將收到訊息“記錄更新成功”,在這種情況下,具有指定電子郵件的用戶的年齡值將更改為32,我們可以看到我們資料庫中的結果。

Delete: Removing Data

The delete operation in PHP is used to remove records from a database table. This operation is performed using the SQL DELETE statement, which specifies the conditions under which records should be deleted. The syntax of the DELETE statement allows you to specify one or more conditions to ensure that only the intended records are removed from the database.

Updated code

<?php

$email = 'person3@example.com';

// Prepare an SQL statement
$stmt = mysqli_prepare($conn, "DELETE FROM users WHERE email=$email");

if ($stmt) {
    // Bind parameter to the prepared statement
    mysqli_stmt_bind_param($stmt, "s", $email);

    // Execute the prepared statement
    if (mysqli_stmt_execute($stmt)) {
        // Verify if any records were deleted using mysqli_stmt_affected_rows
        if (mysqli_stmt_affected_rows($stmt) > 0) {
            echo "Record deleted successfully";
        } else {
            echo "No record found with the specified email.";
        }
    } else {
        // Log the error internally, do not display it to the user
        error_log("Error executing statement: " . mysqli_stmt_error($stmt));
        echo "An error occurred while deleting the record. Please try again later.";
    }

    // Close the statement
    mysqli_stmt_close($stmt);
} else {
    // Log the error internally, do not display it to the user
    error_log("Error preparing statement: " . mysqli_error($conn));
    echo "An error occurred. Please try again later.";
}

// Close the connection
mysqli_close($conn);
?>
登入後複製

Further Reading:

  • Official PHP Documentation
  • W3Schools PHP Tutorial

Conclusion

CRUD operations are the backbone of database interactions in web applications. By mastering these operations, you can build dynamic and interactive applications. I'd love to hear about your experiences with CRUD operations! Share your thoughts in the comments below and let's keep the discussion going.

I want to express my sincere gratitude to each and every one of you who took the time to read this post and share your insights. Your engagement and feedback are incredibly valuable as we continue to learn and grow together.

Don't forget to check out my previous post for more foundational concepts, and feel free to leave your feedback or comments below. Thank you for joining me on this exploration of CRUD operations in PHP.

以上是PHP CRUD 操作初學者指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!