


How 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
- Prerequisites
Before you start, please make sure you have installed PHP and MySQL, and Have the corresponding database.
- 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;
- 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();</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-> ;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;
}
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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,

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's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

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

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

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
