PHP での CRUD 操作の初心者ガイド

王林
リリース: 2024-07-17 12:41:23
オリジナル
1001 人が閲覧しました

導入

PHP は、柔軟で広く使用されているサーバーサイド スクリプト言語であり、今日私たちが目にする多くの動的でインタラクティブな Web ページを強化しています。私自身初心者として、PHP を学ぶ過程は、挑戦的であると同時にやりがいのあるものであると感じています。この投稿では、前の投稿で説明した基本を基に、PHP のより高度なトピックを検討します。

私の最初の投稿「PHP 入門: 初心者ガイド」をまだ読んでいない場合は、ぜひ読んでみてください。開発環境のセットアップ、基本構文の理解、変数とデータ型の操作など、PHP の基礎について説明します。

PHP についてさらに深く掘り下げていく中で、フィードバック、提案、修正を歓迎します。あなたのコメントは私の改善に役立つだけでなく、すべての読者にとって協力的な学習環境を作り出すのにも役立ちます。一緒に PHP の旅を続けましょう!

MySQL データベースのセットアップ

コーディングを開始する前に、MySQL データベースをセットアップする必要があります。 XAMPP がインストールされている場合は、すでに半分まで進んでいます!

XAMPP での MySQL の構成

  1. XAMPP コントロール パネルを開きます: XAMPP コントロール パネルを起動し、「Apache」サービスと「MySQL」サービスを開始します。

  2. XAMPP コントロール パネルを開きます: XAMPP コントロール パネルを起動し、「Apache」サービスと「MySQL」サービスを開始します。

  3. データベースの作成:

  • 左側のサイドバーの「新規」ボタンをクリックします。

  • データベースの名前を入力し、[作成] をクリックします。

CREATE DATABASE データベース名; と記述してデータベースを作成する別のオプションもあります。 SQL スクリプトのコマンドを入力し、[コマンドの実行] をクリックします。

これらの手順を以下に画像付きで示します。

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. テーブルの作成:

  • テーブルの名前を入力します (例: users)。

  • 列数を指定して「実行」をクリックします。

  • 列を定義します (例: 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 コードを含む変数を定義し、MySQLi

などの PHP のデータベース対話ライブラリを使用して変数を実行することで、これらの操作を簡単に実行できます。

作成: データの挿入

コードを更新しました ↓

<?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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!