Home Backend Development PHP Problem How to implement addition, deletion, repair and check in php interface

How to implement addition, deletion, repair and check in php interface

Mar 29, 2023 am 10:09 AM

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

} catch ( PDOException $e) {

echo "Connection failed: " . $e->getMessage();</p>
<p>}</p>
<p>(3) Write query and add, delete and modify operations</p>
<p>// Query all data<br>$stmt = $db-> prepare("SELECT * from user");<br>$stmt->execute();<br>$result = $stmt->fetchAll(PDO::FETCH_ASSOC);</p>
<p>// Get Single piece of data<br>$stmt = $db->prepare("SELECT * from user WHERE id = ?");<br>$stmt->bindParam(1, $_GET['id']);<br>$stmt->execute();<br>$single_result = $stmt->fetch(PDO::FETCH_ASSOC);</p>
<p>// New data<br>$stmt = $db-&gt ;prepare("INSERT INTO user (name, email, phone) VALUES (?, ?, ?)");<br>$stmt->bindParam(1, $_POST['name']);<br>$ stmt->bindParam(2, $_POST['email']);<br>$stmt->bindParam(3, $_POST['phone']);<br>$stmt->execute(); </p>
<p>//Update data<br>$stmt = $db->prepare("UPDATE user SET name = ?, email = ?, phone = ? WHERE id = ?");<br>$stmt ->bindParam(1, $_POST['name']);<br>$stmt->bindParam(2, $_POST['email']);<br>$stmt->bindParam(3, $ _POST['phone']);<br>$stmt->bindParam(4, $_POST['id']);<br>$stmt->execute();</p>
<p>// Delete Data<br>$stmt = $db->prepare("DELETE FROM user WHERE id = ?");<br>$stmt->bindParam(1, $_POST['id']);<br>$ stmt->execute();</p>
<p>(4) Output query results</p>
<p>echo json_encode(['data' => $result]);<br>echo json_encode(['data ' => $single_result]);</p>
<ol start="4"><li>Test interface</li></ol>
<p>Finally, we can use HTTP request tools, such as Postman or Curl, to test whether the interface functions normally. </p>
<p>2. Add security measures</p>
<ol><li>Add Token verification to the interface</li></ol>
<p>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: </p>
<p>Add Token field: </p>
<p>header("Token: xxxxxxx");</p>
<p>Verify Token: </p>
<p>$token = $_SERVER ['HTTP_TOKEN'];<br>if ($token !== 'xxxxxxx') {</p>
<pre class="brush:php;toolbar:false">echo json_encode(['code' => 500, 'msg' => 'Token验证失败']);
exit;
Copy after login

}

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

}

(2) Check the length of the input parameters:

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

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

}

(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 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

How to Use Asynchronous Tasks in PHP for Non-Blocking Operations? How to Use Asynchronous Tasks in PHP for Non-Blocking Operations? Mar 10, 2025 pm 04:21 PM

This article explores asynchronous task execution in PHP to enhance web application responsiveness. It details methods like message queues, asynchronous frameworks (ReactPHP, Swoole), and background processes, emphasizing best practices for efficien

How Do I Stay Up-to-Date with the PHP Ecosystem and Community? How Do I Stay Up-to-Date with the PHP Ecosystem and Community? Mar 10, 2025 pm 06:16 PM

This article explores strategies for staying current in the PHP ecosystem. It emphasizes utilizing official channels, community forums, conferences, and open-source contributions. The author highlights best resources for learning new features and a

How to Use Memory Optimization Techniques in PHP? How to Use Memory Optimization Techniques in PHP? Mar 10, 2025 pm 04:23 PM

This article addresses PHP memory optimization. It details techniques like using appropriate data structures, avoiding unnecessary object creation, and employing efficient algorithms. Common memory leak sources (e.g., unclosed connections, global v

See all articles