search
HomeBackend DevelopmentPHP ProblemHow to implement addition, deletion, repair and check in php interface

In Web development, the role of interfaces is very important. As a common language, PHP is also widely used in network programming and server-side programming. In this article, we will discuss how to use PHP to implement the CRUD interface.

1. Implement the basic CRUD interface

  1. Prerequisites

Before you start, please make sure you have installed PHP and MySQL, and Have the corresponding database.

  1. Create database and data table

First, we need to create a MySQL database and data table. Here we demonstrate using a data table named "user" as an example.

CREATE DATABASE phpapi;
USE phpapi;

CREATE TABLE user (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(20),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  1. Create PHP File

Next, we need to create a PHP file on the server side to implement our interface. We can use the simplest way, which is to write all the logic code in the PHP file and then call it through HTTP request.

(1) Create a file and write header information

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT");
header("Access -Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

(2) Connect to the database

$host = " localhost";
$user = "root";
$password = "";
$dbname = "phpapi";

try {

$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);

} catch ( PDOException $e) {

echo "Connection failed: " . $e->getMessage();

}

(3) Write query and add, delete and modify operations

// Query all data
$stmt = $db-> prepare("SELECT * from user");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get Single piece of data
$stmt = $db->prepare("SELECT * from user WHERE id = ?");
$stmt->bindParam(1, $_GET['id']);
$stmt->execute();
$single_result = $stmt->fetch(PDO::FETCH_ASSOC);

// New data
$stmt = $db-> ;prepare("INSERT INTO user (name, email, phone) VALUES (?, ?, ?)");
$stmt->bindParam(1, $_POST['name']);
$ stmt->bindParam(2, $_POST['email']);
$stmt->bindParam(3, $_POST['phone']);
$stmt->execute();

//Update data
$stmt = $db->prepare("UPDATE user SET name = ?, email = ?, phone = ? WHERE id = ?");
$stmt ->bindParam(1, $_POST['name']);
$stmt->bindParam(2, $_POST['email']);
$stmt->bindParam(3, $ _POST['phone']);
$stmt->bindParam(4, $_POST['id']);
$stmt->execute();

// Delete Data
$stmt = $db->prepare("DELETE FROM user WHERE id = ?");
$stmt->bindParam(1, $_POST['id']);
$ stmt->execute();

(4) Output query results

echo json_encode(['data' => $result]);
echo json_encode(['data ' => $single_result]);

  1. Test interface

Finally, we can use HTTP request tools, such as Postman or Curl, to test whether the interface functions normally.

2. Add security measures

  1. Add Token verification to the interface

In order to increase the security of the interface, we need to add a Token verification mechanism to the interface . The specific implementation method is as follows:

Add Token field:

header("Token: xxxxxxx");

Verify Token:

$token = $_SERVER ['HTTP_TOKEN'];
if ($token !== 'xxxxxxx') {

echo json_encode(['code' => 500, 'msg' => 'Token验证失败']);
exit;

}

  1. Add data verification to the interface

In order to avoid malicious input and illegal operations, we need to verify the interface data. The specific implementation method is as follows:

(1) Type check the input parameters:

if (!is_numeric($_GET['id'])) {

echo json_encode(['code' => 500, 'msg' => '参数类型错误']);
exit;

}

(2) Check the length of the input parameters:

if (strlen($_POST['name']) > 50) {

echo json_encode(['code' => 500, 'msg' => '参数长度错误']);
exit;

}

(3) Filter the SQL statement:

$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email' ], FILTER_SANITIZE_EMAIL);

3. Summary

In this article, we have learned how to use PHP to write a CRUD interface and added some security measures to the interface, such as Token verification. and data verification. I hope these contents can be helpful to you and provide you with reference and guidance in future web development.

The above is the detailed content of How to implement addition, deletion, repair and check in php interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.