この例では、MySQLi 拡張機能を使用してデータベース操作を実行します。
次の SQL スクリプトを実行して、データベースと users という名前のテーブルを作成します。
CREATE DATABASE crud_example; USE crud_example; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE );
データベース接続を管理するための config.php ファイルを作成します。
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "crud_example"; // Conexão com o banco $conn = new mysqli($servername, $username, $password, $dbname); // Verifica conexão if ($conn->connect_error) { die("Falha na conexão: " . $conn->connect_error); } ?>
index.php ファイルを作成してユーザーをリストし、作成、編集、削除の機能を追加します。
<?php include 'config.php'; // Leitura dos dados $sql = "SELECT * FROM users"; $result = $conn->query($sql); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRUD em PHP</title> </head> <body> <h1>Lista de Usuários</h1> <a href="create.php">Adicionar Novo Usuário</a> <table border="1"> <tr> <th>ID</th> <th>Nome</th> <th>Email</th> <th>Ações</th> </tr> <?php while ($row = $result->fetch_assoc()) { ?> <tr> <td><?= $row['id'] ?></td> <td><?= $row['name'] ?></td> <td><?= $row['email'] ?></td> <td> <a href="edit.php?id=<?= $row['id'] ?>">Editar</a> <a href="delete.php?id=<?= $row['id'] ?>" onclick="return confirm('Tem certeza que deseja excluir?')">Excluir</a> </td> </tr> <?php } ?> </table> </body> </html>
create.php ファイルを作成して新しいユーザーを追加します:
<?php include 'config.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; $email = $_POST['email']; $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')"; if ($conn->query($sql) === TRUE) { header("Location: index.php"); exit; } else { echo "Erro: " . $conn->error; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Criar Usuário</title> </head> <body> <h1>Adicionar Novo Usuário</h1> <form method="POST"> <label for="name">Nome:</label> <input type="text"> <hr> <h3> Passo 5: Editar Usuário </h3> <p>Crie um arquivo edit.php para editar um usuário existente:<br> </p> <pre class="brush:php;toolbar:false"><?php include 'config.php'; $id = $_GET['id']; $sql = "SELECT * FROM users WHERE id = $id"; $result = $conn->query($sql); $user = $result->fetch_assoc(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; $email = $_POST['email']; $sql = "UPDATE users SET name='$name', email='$email' WHERE> <hr> <h3> Passo 6: Excluir Usuário </h3> <p>Crie um arquivo delete.php para excluir um usuário:<br> </p> <pre class="brush:php;toolbar:false"><?php include 'config.php'; $id = $_GET['id']; $sql = "DELETE FROM users WHERE> <hr> <h3> Como Rodar o Projeto </h3> <ol> <li>Configure o servidor local (como XAMPP ou LAMP).</li> <li>Coloque todos os arquivos em uma pasta dentro do diretório público (htdocs ou equivalente).</li> <li>Acesse http://localhost/sua_pasta/index.php no navegador.</li> </ol> <p>Esse é um CRUD básico e pode ser melhorado com validações, segurança (como SQL Injection), e estruturação MVC.</p> <hr> <h2> CRUD usando PHP e MySQL, estruturado de forma <strong>orientada a objetos (OOP)</strong> </h2> <p>A abordagem inclui uma classe para gerenciar as operações do banco de dados e separação lógica.</p> <hr> <h3> Passo 1: Configuração da Conexão com o Banco </h3> <p>Crie um arquivo Database.php para encapsular a conexão com o banco:<br> </p> <pre class="brush:php;toolbar:false"><?php class Database { private $host = "localhost"; private $user = "root"; private $pass = ""; private $dbname = "crud_example"; public $conn; public function __construct() { $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->dbname); if ($this->conn->connect_error) { die("Erro na conexão: " . $this->conn->connect_error); } } } ?>
CRUD 操作を管理するための User.php ファイルを作成します:
<?php include 'Database.php'; class User { private $db; public function __construct() { $this->db = (new Database())->conn; } // Create public function create($name, $email) { $stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $email); return $stmt->execute(); } // Read public function getAll() { $result = $this->db->query("SELECT * FROM users"); return $result->fetch_all(MYSQLI_ASSOC); } public function getById($id) { $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute(); return $stmt->get_result()->fetch_assoc(); } // Update public function update($id, $name, $email) { $stmt = $this->db->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?"); $stmt->bind_param("ssi", $name, $email, $id); return $stmt->execute(); } // Delete public function delete($id) { $stmt = $this->db->prepare("DELETE FROM users WHERE id = ?"); $stmt->bind_param("i", $id); return $stmt->execute(); } } ?>
ユーザーのリストを表示し、ナビゲーションを管理するために、index.php ファイルを作成します。
<?php include 'User.php'; $user = new User(); $users = $user->getAll(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRUD OOP PHP</title> </head> <body> <h1>Lista de Usuários</h1> <a href="create.php">Adicionar Novo Usuário</a> <table border="1"> <tr> <th>ID</th> <th>Nome</th> <th>Email</th> <th>Ações</th> </tr> <?php foreach ($users as $u) { ?> <tr> <td><?= $u['id'] ?></td> <td><?= $u['name'] ?></td> <td><?= $u['email'] ?></td> <td> <a href="edit.php?id=<?= $u['id'] ?>">Editar</a> <a href="delete.php?id=<?= $u['id'] ?>" onclick="return confirm('Deseja excluir este usuário?')">Excluir</a> </td> </tr> <?php } ?> </table> </body> </html>
create.php ファイルを作成して新しいユーザーを追加します:
<?php include 'User.php'; $user = new User(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; $email = $_POST['email']; if ($user->create($name, $email)) { header("Location: index.php"); exit; } else { echo "Erro ao criar usuário."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Criar Usuário</title> </head> <body> <h1>Adicionar Novo Usuário</h1> <form method="POST"> <label for="name">Nome:</label> <input type="text"> <hr> <h3> Passo 5: Editar Usuário </h3> <p>Crie um arquivo edit.php para atualizar os dados do usuário:<br> </p> <pre class="brush:php;toolbar:false"><?php include 'User.php'; $user = new User(); $id = $_GET['id']; $data = $user->getById($id); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; $email = $_POST['email']; if ($user->update($id, $name, $email)) { header("Location: index.php"); exit; } else { echo "Erro ao atualizar usuário."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Editar Usuário</title> </head> <body> <h1>Editar Usuário</h1> <form method="POST"> <label for="name">Nome:</label> <input type="text"> <hr> <h3> Passo 6: Excluir Usuário </h3> <p>Crie um arquivo delete.php para deletar um usuário:<br> </p> <pre class="brush:php;toolbar:false"><?php include 'User.php'; $user = new User(); $id = $_GET['id']; if ($user->delete($id)) { header("Location: index.php"); exit; } else { echo "Erro ao excluir usuário."; } ?>
この例はオブジェクト指向 CRUD の基礎であり、入力検証、より堅牢なエラー処理、名前空間の使用などの適切な実践により改善できます。
ここでは、PHP で 2 つの API を作成する方法の例を示します。1 つは バックエンド API として使用され、もう 1 つは クライアント として最初の API を使用します。
データベースにユーザーテーブルを作成します:
CREATE DATABASE api_example; USE api_example; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE );
エンドポイントを使用できるようにするために、api.php というファイルを作成します。
<?php header("Content-Type: application/json"); include 'Database.php'; class UserAPI { private $db; public function __construct() { $this->db = (new Database())->conn; } public function handleRequest() { $method = $_SERVER['REQUEST_METHOD']; $endpoint = $_GET['endpoint'] ?? ''; switch ($endpoint) { case 'users': if ($method === 'GET') { $this->getUsers(); } elseif ($method === 'POST') { $this->createUser(); } else { $this->response(405, "Method Not Allowed"); } break; default: $this->response(404, "Endpoint Not Found"); } } private function getUsers() { $result = $this->db->query("SELECT * FROM users"); $users = $result->fetch_all(MYSQLI_ASSOC); $this->response(200, $users); } private function createUser() { $input = json_decode(file_get_contents("php://input"), true); if (empty($input['name']) || empty($input['email'])) { $this->response(400, "Missing required fields: name or email"); return; } $stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $input['name'], $input['email']); if ($stmt->execute()) { $this->response(201, "User created successfully"); } else { $this->response(500, "Internal Server Error"); } } private function response($status, $data) { http_response_code($status); echo json_encode(["status" => $status, "data" => $data]); } } $api = new UserAPI(); $api->handleRequest(); ?>
バックエンド API を使用するために client.php というファイルを作成します。
CREATE DATABASE crud_example; USE crud_example; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE );
この例は機能ベースです。実稼働環境では、次のことをお勧めします。
PHP と MySQL の若手開発者向けの技術面接の準備をしている場合は、通常取り上げられる主なトピックといくつかのヒントを以下に示します。
中堅企業もソフトスキルを評価します。次のような質問に備えてください:
以上がCRUD PHP、MySQL、API、および重要な基礎の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。