Home Backend Development PHP Tutorial Create a CRUD application using PHP and MySQL

Create a CRUD application using PHP and MySQL

May 11, 2023 pm 03:33 PM
mysql php CRUD

With the development of the Internet, Web applications have become a necessity in our daily life and work. With the help of PHP and MySQL, we can easily create a web-based application that allows users to add, delete, modify and view data. This article will introduce how to use PHP and MySQL to create a simple CRUD application.

  1. Create database and tables

First, we need to create a database and a related table. Open PHPMyAdmin or other MySQL management tools, create a new database, name it "crud", and set the character set to "utf8mb4_general_ci".

Next, we need to create a table to store our data. Let's assume we want to create a simple user management system with the following fields: id, username, email address, and password. We can use the following SQL statement to create this table:

CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(50) NOT NULL,
email varchar(100) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

  1. Connect to the database

Now, we have After creating the database and tables, we need to connect to the database. In PHP, we can use mysqli or PDO extension to implement database connection. Here we will use the mysqli extension. Here is sample code to connect to the database:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "crud";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection successful";
?> ;

  1. Display data

Now that we are connected to the database, we can start writing code to display the data. The following is sample code to display user data:

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Output data
while($row = $result->fetch_assoc()) {

echo "id: " . $row["id"]. " - 用户名: " . $row["username"]. " - 邮箱地址: " . $row["email"]. "<br>";

}
} else {
echo "0 result";
}
$conn->close();
?>

  1. Add data

Now that we know how to display data, we can write code to add data. Here is sample code to add user data:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username" ];
$email = $_POST["email"];
$password = $_POST["password"];

$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";

if ($conn->query($sql) === TRUE) {

echo "新记录添加成功";

} else {

echo "错误: " . $sql . "<br>" . $conn->error;

}

$conn->close();
}
?>

  1. Update data

Now that we know how to add data, we can write code to update the data. Here is sample code to update user data:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST["id" ];
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];

$sql = "UPDATE users SET username='$username', email='$email', password='$password' WHERE id=$id";

if ($conn->query($ sql) === TRUE) {

echo "记录更新成功";

} else {

echo "错误: " . $sql . "<br>" . $conn->error;

}

$conn->close();
}
?> ;

  1. Delete data

Finally, we need to know how to delete data. Here is sample code to delete user data:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST["id" ];

$sql = "DELETE FROM users WHERE id=$id";

if ($conn->query($sql) === TRUE) {

echo "记录删除成功";

} else {

echo "错误: " . $sql . "<br>" . $conn->error;

}

$conn->close();
}
?>

We already know how to create A basic CRUD application. Of course, this is just a simple example. In practical applications, we need to carry out more functional expansion and implementation according to actual needs.

The above is the detailed content of Create a CRUD application using PHP and MySQL. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to read a CSV file in PHP? How to read a CSV file in PHP? Aug 29, 2025 am 08:06 AM

ToreadaCSVfileinPHP,usefopen()toopenthefile,fgetcsv()inalooptoreadeachrowasanarray,andfclose()tocloseit;handleheaderswithaseparatefgetcsv()callandspecifydelimitersasneeded,ensuringproperfilepathsandUTF-8encodingforspecialcharacters.

How to use AJAX with php How to use AJAX with php Aug 29, 2025 am 08:58 AM

AJAXwithPHPenablesdynamicwebappsbysendingasynchronousrequestswithoutpagereloads.1.CreateHTMLwithJavaScriptusingfetch()tosenddata.2.BuildaPHPscripttoprocessPOSTdataandreturnresponses.3.UseJSONforcomplexdatahandling.4.Alwayssanitizeinputsanddebugviabro

What is the difference between isset and empty in php What is the difference between isset and empty in php Aug 27, 2025 am 08:38 AM

isset()checksifavariableexistsandisnotnull,returningtrueevenforzero,false,oremptystringvalues;2.empty()checksifavariableisnull,false,0,"0","",orundefined,returningtrueforthese"falsy"values;3.isset()returnsfalsefornon-exi

How to configure SMTP for sending mail in php How to configure SMTP for sending mail in php Aug 27, 2025 am 08:08 AM

Answer: Using the PHPMailer library to configure the SMTP server can enable sending mails through SMTP in PHP applications. PHPMailer needs to be installed, set up SMTP host, port, encryption method and authentication credentials of Gmail, write code to set sender, recipient, topic and content, enable 2FA and use application password to ensure that the server allows SMTP connection, and finally call the send method to send email.

How to get the current date and time in PHP? How to get the current date and time in PHP? Aug 31, 2025 am 01:36 AM

Usedate('Y-m-dH:i:s')withdate_default_timezone_set()togetcurrentdateandtimeinPHP,ensuringaccurateresultsbysettingthedesiredtimezonelike'America/New_York'beforecallingdate().

How to create an object in php How to create an object in php Aug 27, 2025 am 08:45 AM

To create a PHP object, you need to define the class first, and then instantiate it with the new keyword. For example, after defining the Car class and setting properties and constructing methods, create an object through $myCar=newCar("red","Toyota"), and then use -> to access its properties and methods, such as $myCar->color and $myCar->showInfo(). Each object has independent data and can create multiple instances.

How to set an error reporting level in PHP? How to set an error reporting level in PHP? Aug 31, 2025 am 06:48 AM

Useerror_reporting()toseterrorlevelsinPHP,suchasE_ALLfordevelopmentor0forproduction,andcontroldisplayorloggingviaini_set()toenhancedebuggingandsecurity.

How to use the spaceship operator () in PHP? How to use the spaceship operator () in PHP? Aug 29, 2025 am 06:31 AM

PHP's spaceship operator is used to compare two values, returning -1, 0 or 1: when the left operand is smaller than the right operand, return -1, when equal to 0, and when greater than 1. It supports types such as numbers and strings, and is often used in sorting scenarios such as usort, making the multi-level sorting logic more concise and clear, and is available since PHP7.0.

See all articles