PHP의 CRUD 작업 초보자 가이드

王林
풀어 주다: 2024-07-17 12:41:23
원래의
1080명이 탐색했습니다.

소개

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 작업 수행

웹 개발 환경에서 CRUD 작업을 수행한다는 것은 데이터베이스에 저장된 데이터에 대해 수행할 수 있는 기본 작업(생성, 읽기, 업데이트, 삭제)을 의미합니다. 이러한 작업은 사용자가 데이터와 상호 작용할 수 있는 동적 및 대화형 웹 애플리케이션을 구축하는 데 기본입니다. CRUD 작업은 웹 애플리케이션의 데이터베이스 상호 작용의 백본입니다. 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!