Home Database Mysql Tutorial CRUD PHP and MySQL and API and Important Fundamentals

CRUD PHP and MySQL and API and Important Fundamentals

Dec 31, 2024 pm 01:23 PM

CRUD PHP e MySQL e API e Fundamentos importantes

How to create a CRUD (Create, Read, Update, Delete) in PHP with MySQL.

This example uses the MySQLi extension to perform database operations.

Step 1: Creating the Database and Table

Run the following SQL script to create the database and a table called 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
);
Copy after login
Copy after login

Step 2: Connection to the Database

Create a config.php file to manage the database connection:

<?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);
}
?>
Copy after login

Step 3: Home Page

Create an index.php file to list users and add creation, editing and deletion functionality:

<?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>
Copy after login

Step 4: Create User

Create a create.php file to add a new user:

<?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);
        }
    }
}
?>
Copy after login

Step 2: Class for Bank Operations

Create a User.php file to manage CRUD operations:

<?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();
    }
}
?>
Copy after login

Step 3: Home Page

Create an index.php file to display the list of users and manage navigation:

<?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>
Copy after login

Step 4: Create User

Create a create.php file to add new users:

<?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.";
}
?>
Copy after login

How to Run the Project

  1. Set up local server (like XAMPP or LAMP).
  2. Create the database using SQL at first.
  3. Place all files in a folder in the public directory.
  4. Go to http://localhost/your_pasta/index.php in your browser.

This example is a basis for an object-oriented CRUD and can be improved with good practices, such as input validation, more robust error handling, and the use of namespaces.

Here is an example of how to create two APIs in PHP: one backend API to be consumed and another as client to consume the first API.


Creating the API to be consumed (Backend)

Step 1: Database Structure

Create a users table in the database:

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
);
Copy after login

Step 2: API Backend

Create a file called api.php to make the endpoints available.

<?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();
?>
Copy after login

2. Creating the Client to Consume API

API Client

Create a file called client.php to consume the backend API.

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
);
Copy after login
Copy after login

3. Testing the API

Step 1: Configure the local environment

  1. Set up your local server (XAMPP, LAMP or similar).
  2. Place the api.php and client.php files in the same public folder.

Step 2: Test

  1. API Backend: Go to http://localhost/api.php?endpoint=users to check the API endpoint.
  2. Client: Run the client.php file in the terminal or through the browser to test consumption.

This example is a functional basis. For production, it is recommended:

  • Use authentication tokens (like JWT).
  • Add data validation and sanitization.
  • Improve error management and HTTP responses.

If you are preparing for a technical interview for a junior developer with PHP and MySQL, here are the main topics that are usually covered, plus some tips:


PHP Fundamentals

  • Basic syntax: Knowledge about variables, arrays, strings, loops, functions and control structures.
  • Built-in functions: Manipulation of strings (e.g., explode, implode, trim), arrays (array_merge, array_filter) and numbers (round, rand).
  • Object Orientation (OOP): Classes, objects, inheritance, encapsulation, polymorphism and interfaces.
  • Working with files: fopen, fwrite, file_get_contents.
  • Error and exception handling: try-catch and how to handle errors in PHP.
  • Superglobals: $_POST, $_GET, $_SESSION, $_COOKIE, and how to use them.

2. MySQL and PHP Integration

  • Basic queries: SELECT, INSERT, UPDATE, DELETE, with and without clauses such as WHERE, ORDER BY and LIMIT.
  • Joins: Know how to use INNER JOIN, LEFT JOIN, RIGHT JOIN.
  • Relationships: Work with related tables (1:1, 1:N, N:N).
  • CRUD with PDO or MySQLi: Knowledge in executing queries and protecting against SQL Injection using prepared queries.
  • Indices: What they are and how they help performance.
  • Transactions: Concept and use in MySQL (START TRANSACTION, COMMIT, ROLLBACK).

3. Data Structure and Logic

  • Basic algorithms: Sorting (Bubble Sort, Quick Sort), search (binary, linear).
  • Data structures: Arrays, stacks, queues, lists.
  • Troubleshooting: Experience solving small logic problems, such as those found in technical challenges (e.g., HackerRank, Codewars).

4. Good Practices and Standards

  • Clean Code: Use of descriptive variable and function names, well-indented code.
  • DRY (Don't Repeat Yourself) and KISS (Keep It Simple, Stupid).
  • Basic security: Prevention against SQL Injection, XSS and CSRF.

5. Web Development

  • Basic HTML/CSS/JavaScript: Sufficient knowledge to work with backends that interact with frontends.
  • Forms: Forms processing, server-side validation.
  • RESTful APIs: How to create and consume APIs, HTTP methods (GET, POST, PUT, DELETE).
  • Sessions and authentication: Using $_SESSION and basic login/logout management.

6. Tools and Environment

  • Versioning with Git: Commit, branch, merge and how to create pull requests.
  • PHP Composer: Understand how to use external dependencies.
  • Local environment: Experience with WAMP, XAMPP or Docker.
  • Debugging: Use of var_dump, print_r, or tools like Xdebug.

7. Basic Concepts of Software Engineering

  • Architecture models: MVC (Model-View-Controller).
  • Relational database: Normalization of tables, primary and foreign keys.
  • Version control: Work with Git repositories and understand team workflow (e.g., Git Flow).

8. Behavioral Questions

Junior companies also evaluate soft skills. Prepare for questions like:

  • Why did you choose PHP?
  • How do you solve problems under pressure?
  • Tell me about a project you have already developed.
  • How do you deal with errors?

Tips to Stand Out

  1. Design something practical before the interview: Example, a simple CRUD, a RESTful API, or a basic login system. This shows your proactivity.
  2. Get to know the company: Understand what it does, its technologies and see if you can align your answers with your needs.
  3. Be honest: It's normal not to know everything. Demonstrate a willingness to learn and how you resolve gaps in knowledge.

The above is the detailed content of CRUD PHP and MySQL and API and Important Fundamentals. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Difference between clustered index and non-clustered index (secondary index) in InnoDB. Difference between clustered index and non-clustered index (secondary index) in InnoDB. Apr 02, 2025 pm 06:25 PM

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values ​​and pointers to data rows, and is suitable for non-primary key column queries.

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Can mysql and mariadb coexist Can mysql and mariadb coexist Apr 08, 2025 pm 02:27 PM

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Apr 02, 2025 pm 07:05 PM

MySQL supports four index types: B-Tree, Hash, Full-text, and Spatial. 1.B-Tree index is suitable for equal value search, range query and sorting. 2. Hash index is suitable for equal value searches, but does not support range query and sorting. 3. Full-text index is used for full-text search and is suitable for processing large amounts of text data. 4. Spatial index is used for geospatial data query and is suitable for GIS applications.

See all articles