Dashboard

CRUD на PHP для работы с MySQL: пошаговый урок для начинающих

В этой статье мы рассмотрим разработку простого набора CRUD операций на PHP, предназначенного для работы с базой данных MySQL. Для создания кода CRUD будет использовано расширение MySQLi, для оформления – стили Bootstrap. Приложение будет выполнять все стандартные операции CRUD – создание, чтение, модификацию и удаление записей.

Что такое CRUD: это аббревиатура, обозначающая четыре главные операции, используемые в приложениях для управления базами данных – создание (create), чтение (read), модификацию (update) и удаление (delete) записей.

Итак, приступим к разработке CRUD на PHP и MySQLi с нуля.

Шаг 1: Создание таблицы базы данных

Приведенная ниже SQL команда создает таблицу с данными пользователей в базе MySQL.

CREATE TABLE users ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, email VARCHAR(255) NOT NULL, phone_number VARCHAR(15) NOT NULL, address VARCHAR(255) NOT NULL );

Шаг 2: Создание файла конфигурации

После создания таблицы мы переходим к настройке подключения к серверу базы данных MySQL. Для этого нужно создать файл config.php и поместить в него приведенный ниже код.

Это подключение можно вызывать на всех страницах – с помощью PHP функции require_once() .

Шаг 3: Посадочная страница

На посадочной странице данные пользователей будут выводиться в виде таблицы. Мы предусмотрим иконки для операций редактирования, просмотра и удаления данных.

Для создания лендинга мы добавим файл index.php в директорию CRUD. Вставьте в файл данный ниже код.

      .wrapper  

PHP CRUD Tutorial Example with Coding Driver

Users

Add New User
0) < echo ""; while($user = mysqli_fetch_array($users)) < echo ""; > echo "
# First Name Last Name Email Phone Number Address Action
" . $user['id'] . " " . $user['first_name'] . " " . $user['last_name'] . " " . $user['email'] . " " . $user['phone_number'] . " " . $user['address'] . "
"; mysqli_free_result($users); > else< echo "

No records found.

"; > > else < echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn); >// Close connection mysqli_close($conn); ?>

Можно вставить какие-нибудь тестовые данные прямо в таблицу базы данных, изменения отобразятся на странице.

Шаг 4: Страница создания записей

На этом этапе мы разработаем CRUD операцию по созданию записей. Для этого создайте новый файл под названием create.php и поместите в него следующий код:

 elseif (!filter_var($firstName, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) < $first_name_error = "First Name is invalid."; >else < $firstName = $firstName; >$lastName = trim($_POST["last_name"]); if (empty($lastName)) < $last_name_error = "Last Name is required."; >elseif (!filter_var($firstName, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) < $last_name_error = "Last Name is invalid."; >else < $lastName = $lastName; >$email = trim($_POST["email"]); if (empty($email)) < $email_error = "Email is required."; >elseif (!filter_var($firstName, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) < $email_error = "Please enter a valid email."; >else < $email = $email; >$phoneNumber = trim($_POST["phone_number"]); if(empty($phoneNumber)) < $phone_number_error = "Phone Number is required."; >else < $phoneNumber = $phoneNumber; >$address = trim($_POST["address"]); if(empty($address)) < $address_error = "Address is required."; >else < $address = $address; >if (empty($first_name_error_err) && empty($last_name_error) && empty($email_error) && empty($phone_number_error) && empty($address_error) ) < $sql = "INSERT INTO `users` (`first_name`, `last_name`, `email`, `phone_number`, `address`) VALUES ('$firstName', '$lastName', '$email', '$phoneNumber', '$address')"; if (mysqli_query($conn, $sql)) < header("location: index.php"); >else < echo "Something went wrong. Please try again later."; >> mysqli_close($conn); > ?>      .wrapper  

Create User

Cancel

Файл create.php будет отображать HTML форму для ввода и валидации данных.

Шаг 5: Страница модификации записей

По аналогии со страницей создания записей мы разработаем функцию и страницу модификации данных. Создайте файл с именем edit.php и вставьте в него приведенный ниже код, который обеспечивает редактирование записей, уже существующих в базе данных.

 elseif (!filter_var($firstName, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) < $first_name_error = "First Name is invalid."; >else < $firstName = $firstName; >$lastName = trim($_POST["last_name"]); if (empty($lastName)) < $last_name_error = "Last Name is required."; >elseif (!filter_var($firstName, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) < $last_name_error = "Last Name is invalid."; >else < $lastName = $lastName; >$email = trim($_POST["email"]); if (empty($email)) < $email_error = "Email is required."; >elseif (!filter_var($firstName, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) < $email_error = "Please enter a valid email."; >else < $email = $email; >$phoneNumber = trim($_POST["phone_number"]); if (empty($phoneNumber)) < $phone_number_error = "Phone Number is required."; >else < $phoneNumber = $phoneNumber; >$address = trim($_POST["address"]); if (empty($address)) < $address_error = "Address is required."; >else < $address = $address; >if (empty($first_name_error_err) && empty($last_name_error) && empty($email_error) && empty($phone_number_error) && empty($address_error) ) < $sql = "UPDATE `users` SET `first_name`= '$firstName', `last_name`= '$lastName', `email`= '$email', `phone_number`= '$phoneNumber', `address`= '$address' WHERE "; if (mysqli_query($conn, $sql)) < header("location: index.php"); >else < echo "Something went wrong. Please try again later."; >> mysqli_close($conn); > else < if (isset($_GET["id"]) && !empty(trim($_GET["id"]))) < $id = trim($_GET["id"]); $query = mysqli_query($conn, "SELECT * FROM users WHERE "); if ($user = mysqli_fetch_assoc($query)) < $firstName = $user["first_name"]; $lastName = $user["last_name"]; $email = $user["email"]; $phoneNumber = $user["phone_number"]; $address = $user["address"]; >else < echo "Something went wrong. Please try again later."; header("location: edit.php"); exit(); >mysqli_close($conn); > else < echo "Something went wrong. Please try again later."; header("location: edit.php"); exit(); >> ?>      .wrapper  

Update User

"/>
">
">
">
">
Cancel

Шаг 6: Чтение записей

Для вывода на экран данных пользователей мы разработаем функцию чтения записей. Создайте файл read.php , сохраните в нем данный ниже код. Файл будет запрашивать данные пользователей по ID из таблицы базы данных.

      .wrapper  else < header("location: read.php"); exit(); >mysqli_close($conn); > else < header("location: read.php"); exit(); >?> 

User View

Back

Шаг 7: Удаление записей

На заключительном этапе мы разработаем функцию удаления записей. Создайте файл delete.php , вставьте в него приведенный ниже код, который отвечает за удаление существующих в базе записей по ID пользователя.

 else < echo "Something went wrong. Please try again later."; >mysqli_close($conn); > else < if (empty(trim($_GET["id"]))) < echo "Something went wrong. Please try again later."; header("location: index.php"); exit(); >> ?>      .wrapper  

Delete Record

"/>

Are you sure you want to delete this record?


No

Наконец, наш набор CRUD операций для работы с записями в базе данных MySQL готов. Если у вас есть вопросы или замечания – ждем их в комментариях.

Наталья Кайда автор-переводчик статьи « PHP MySQL CRUD Operation Step by Step for Beginners »

Пожалуйста, опубликуйте ваши мнения по текущей теме материала. За комментарии, подписки, дизлайки, отклики, лайки огромное вам спасибо!

Источник

Create CRUD Application in PHP using MySQL for Beginners

PHP-CRUD-application

This article will help you learn how to create a simple and easy CRUD application in PHP using MySQL.

CRUD is an acronym for CREATE, READ, UPDATE, DELETE. We perform all these operations to manipulate the data in the database. Using PHP, we are going to create an application that performs all the CRUD operations.

To create and run our application, first, we need to set up our system with the following.

Once you have all that set up, we can start working on our application.

Let’s first begin with our frontend

We have created a landing page( index.php ) to make our application look a bit professional.

php crud landing page

You can start with the homepage, displaying all our data records in a tabular format. All the data from our user’s table will have an action button on each record to perform the READ, UPDATE and DELETE operation. We will also add an “Add New User” button to CREATE a new user.

Create a folder named “includes”. Then create a file named home.php with the following code add it into the “includes” folder.

crud-operation-homepage

  
Data to perform CRUD Operations Create New User "; echo " "; echo " "; echo " "; echo " "; > ?>
ID Username Email Password
"; echo " "; echo " "; echo " "; echo " View ' btn-secondary'> EDIT DELETE
Back

We are also going to create common header and footer pages to add those to other pages when required and avoid rewriting the same code repeatedly.
So, create a file header.php and add the following code

[email protected]/dist/css/bootstrap.min.css» rel=»stylesheet» integrity=»sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6″ crossorigin=»anonymous»> [email protected]/font/bootstrap-icons.css»>

Create a file footer.php and add the following code

Now Let’s set up our database

If you know your way around XAMPP, create a database “php_crud” and create a user table with four columns (ID, username, email, and password). Else you can execute a SQL query to create the table.

Creating the Database and User Table

1. first, open the XAMPP server and start 2 services ( Apache and MySQL).

XAMPP control panel

2. Then click on Admin, or you can type in the URL “localhost/phpmyadmin/”

xampp open phpmyadmin

3. Click on either “new” or “Databases,” and enter your database name ( we are using ‘php_crud’ ) and click Create.

creating database in phpmyadmin

4. Now, click on “SQL,” enter the following code and click “Go.”

CRUD Application in php - creating table with SQL query

CREATE TABLE users( ID int NOT NULL AUTO_INCREMENT, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY (ID) );

Now, Let’s Work on CRUD

Creating the Database Connection File

Now we are going to connect our MySQL database using a PHP script. Open your code editor, create a file db.php ( you can name it whatever you want ), and add the following code.

  1. define the server and database details like database name, server name, username, and password.
  2. mysqli_connect” function attempts the connection to MySQL Database.
  3. In case the connection fails this “mysqli_connect_error()” function display’s an error message.

NOTE: If you have a different username, password, or database name, make sure you replace them with the correct credentials. For example, if you have created a different database name then replace php_crud with your database name.

Creating the Create Page

Let’s build the create function of our php CRUD application. Create a file create.php with the following code and add it into the “includes” folder. It will create a form for the user to insert details like name, email and save the input data into the users’ table.

  ','','')"; $add_user = mysqli_query($conn,$query); // displaying proper message for the user to see whether the query executed perfectly or not if (!$add_user) < echo "something went wrong ". mysqli_error($conn); >else < echo ""; > > ?> 

Back

Creating the Read Page

Now that we have some data in our table let’s build the read function of our php CRUD application. Create a read.php file with the following code and add it into the “includes” folder. It will retrieve and show the data that we have stored in our table based on the ID attribute of the user.

   

ID Username Email Password "; echo " "; echo " "; echo " "; echo " "; echo " "; > > ?>
Back

Creating the Update Page

Now let’s build the update function of our php CRUD application. Create a update.php file with the following code and add it into the “includes” folder.

It will retrieve the data that we have stored in our table based on the ID attribute of the user and show it in the form, from which we can update the data and save it back to the users’ table.

   // SQL query to select all the data from the table where $query="SELECT * FROM users WHERE "; $view_users= mysqli_query($conn,$query); while($row = mysqli_fetch_assoc($view_users)) < $id = $row['id']; $user = $row['username']; $email = $row['email']; $pass = $row['password']; >//Processing form data when form is submitted if(isset($_POST['update'])) < $user = $_POST['user']; $email = $_POST['email']; $pass = $_POST['pass']; // SQL query to update the data in user table where the $query = "UPDATE users SET username = '' , email = '' , password = '' WHERE $update_user = mysqli_query($conn, $query); echo ""; > ?> 

Username ">
Email ID ">
We'll never share your email with anyone else.
Password ">
Back

Creating the Delete Page

Finally, we can build the delete function of our php CRUD application. Create a delete.php file with the following code and add it into the “includes” folder.

It will delete the data that we have stored in our table based on the ID attribute of the user.

That’s it! You’re all set!
You now know how to create a PHP CRUD Application with MySQL.

Note: We have used Procedural method to create the CRUD Application. But if you want this application in Object-Oriented, then download it from here.

We hope this article helps you understand how to create a CRUD application using PHP and MySQL. If you find it helpful, don’t forget to share this article with your friends.
If you find any mistake or something didn’t work out quite right, do let us know. Thank You for reading!

Источник

Читайте также:  File opening in php example
Оцените статью