Home Backend Development PHP Problem How PHP+MySQL implements database addition, deletion, modification and query operations

How PHP+MySQL implements database addition, deletion, modification and query operations

Mar 23, 2023 pm 04:53 PM
mysql php database

PHP and MySQL are the most popular technologies in modern web development. By using these two technologies, developers can build dynamic web applications that include data storage and retrieval. This article will introduce how to use PHP and MySQL to implement add, delete, modify and query operations in the database.

1. Environment configuration

Before we start, we need to confirm that the development environment for PHP and MySQL has been configured. If not, please install and configure it yourself. In order to test the code, we use the local environment for development, and assume that you have already set up the web server, PHP and MySQL locally.

2. Create the database

First, we need to create the database. Please use the MySQL client to log in to the server and run the following command in the console:

CREATE DATABASE test;
Copy after login

This will create a database named "test". Next, we need to switch to this database:

USE test;
Copy after login

Next, we will create a data table named "users", which will contain the user's information.

CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Copy after login

This will create a data table named "users", which contains four fields: id, name, email and password. id is an auto-incrementing integer used as a unique identifier for the user. The name and email fields store the user's name and email address respectively. The password field stores the user's password, which needs to be hashed and stored. The created_at field is used to store the creation time of the user account.

3. Configure database connection

In PHP, we use the mysqli extension to manage our database connection. First, we need to define some constants to store the configuration values ​​​​of the database connection. In this example, we will connect to the local MySQL server with the username root, password empty, and database name test:

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'test');
Copy after login

Next, we use the mysqli_connect() function to connect to the database server:

$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Copy after login

If the connection fails, an error message will be returned. If successful, the following four basic database operations can be performed: create, read, update, and delete.

4. Implement add, delete, modify and query operations

  1. Add to database

The following functions are used to add user information to the data In the table:

function create_user($name, $email, $password) {
global $mysqli;

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

$stmt = $mysqli->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $hashed_password);
$stmt->execute();

return $mysqli->insert_id;
}
Copy after login

This function requires three parameters: username, email address and password. It first hashes the password using the password_hash() function. Then, use the prepare() function to prepare a SQL query that will add the username, email address, and hashed password to the data table. The bind_param() function binds parameters to query placeholders and executes the query. Finally, use the insert_id() function to obtain the new user's unique identifier.

  1. Get data from the database

The following function obtains user information in the database through the user's ID:

function get_user($id) {
global $mysqli;

$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows === 0) {
    return null;
}

return $result->fetch_assoc();
}
Copy after login

This function requires one parameter: The user's unique identifier. It uses the prepare() function to prepare a SQL query that will select user information in the data table that matches the provided ID. The bind_param() function binds parameters to query placeholders and executes the query. Then use the get_result() function to get the query results and return an associative array (if the record is found) or null (if the record is not found).

  1. Update database

The following function is used to update user information in the database:

function update_user($id, $name, $email, $password) {
global $mysqli;

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

$stmt = $mysqli->prepare("UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?");
$stmt->bind_param("sssi", $name, $email, $hashed_password, $id);
$stmt->execute();

return $stmt->affected_rows === 1;
}
Copy after login

This function requires four parameters: user ID, user name , email address and password. It first hashes the password using the password_hash() function. Then, use the prepare() function to prepare a SQL query that will update the user information in the data table that matches the provided ID. The bind_param() function binds parameters to query placeholders and executes the query. Finally, use the affected_rows() function to check whether the update is successful and return a Boolean value.

  1. Delete data from the database

The following function is used to delete user information from the database:

function delete_user($id) {
global $mysqli;

$stmt = $mysqli->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

return $stmt->affected_rows === 1;
}
Copy after login

This function requires one parameter: user ID. It uses the prepare() function to prepare a SQL query that will delete user information matching the provided ID from the data table. The bind_param() function binds parameters to query placeholders and executes the query. Finally, use the affected_rows() function to check whether the deletion is successful and return a Boolean value.

5. Debugging and Optimization

In any web development process, debugging and optimization are very important. In order to debug our code, we can use the error_reporting() and ini_set() functions. These functions are used to set the error reporting level and settings for displaying error messages. In order to optimize our code, we should avoid concatenated strings in database queries as much as possible, and should use the prepare() function and bind_param() function instead.

6. Summary

By using PHP and MySQL, we can easily create web applications with data storage and retrieval capabilities. In this article, we covered how to use these two technologies to implement basic database operations: create, read, update, and delete. By implementing the above code, you will learn how to connect to the database, create database tables, add, read, update and delete user data. These skills will be very useful in your future web development jobs.

The above is the detailed content of How PHP+MySQL implements database addition, deletion, modification and query operations. 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)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles