0% found this document useful (0 votes)
137 views70 pages

PHP CRUD Tutorial

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views70 pages

PHP CRUD Tutorial

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

PHP CRUD TUTORIAL

Table of contents:
I. Tools Needed……………………………………………………
II. Overview of CRUD…………………………………………….
1. Folder Structure…………………………………………………
➢ Steps involved in creating a folder
2. Opening of folder in the working environment…………………
3. Creating the files…………………………………………………
4. PHP MySQL Database Creating Database and Tables………….
5. Data Manipulation………………………………………………
Inserting/Adding
i.
data
ii.
Reading Data
iii
Updating Data
.
iv. Deleting Data

TOOLS REQUIRED TO BEGIN IN PHP DEVELOPMENT


To begin constructing a website in PHP, we will need the following items.

Apache Server - A web server is a computer program that provides (serves) content, such as web
pages, over the World Wide Web using the Hypertext Transfer Protocol (HTTP).
The computer or virtual machine that runs the program is also referred to as a web server.

MySQL Database - This is where you'll keep all of your crucial data. MySQL is fast, simple to
use, safe, adaptable, and completely free.

PHP is a popular general-purpose scripting language that was created for web development to
create dynamic web sites.

Step 1
Download and install XAMPP (Lecturer will assist you to install this application).

Step 2
XAMPP Control Panel Application
Run XAMPP Control Panel, and start running Apache and MySQL.
Localhost
Open up a browser (Firefox, Internet Explorer, Safari, Google Chrome, or etc…) type and go
to this address: “localhost” (without quotes).

If you have installed the XAMPP successfully. You’ll see XAMPP on your browser in
“localhost” address. (See screenshot above).
Step 3:
Install the PHP IDE (integrated development environment)

An IDE is a software application that provides full software development features to computer
programmers.SI recommend using Sublime Text.
(Lecturer will assist you with the setup and the installation)

IV
OVERVIEW OF CRUD

CRUD is an acronym for the four basic types of SQL commands: Create, Read, Update,
Delete. Most applications have some kind of CRUD functionality, and we can assume that
every programmer had to deal with CRUD at some point. A CRUD application is one that
uses forms to get data into and out of a database.
In this project, we will be working with PHP and MySQL database and build a simple web
application.
We are going to create a database with MySQL and create a table inside the database. After
creating the database, we then use PHP to talk to the database. In the process of talking to
the database, we will tell PHP to tell MySQL to Create, Read, Update and Delete (CRUD)
information from the table inside the database for us. That is all about the project. By the end
of this project, you should be able to PHP to Create, Read, Update and Delete any
information from the table inside the database. If you are ready let get stated;

1
FOLDER STRUCTURE
The first thing to do when working with PHP on any project is to get a folder for the project.
If you have installed XAMPP successfully, a folder will be created on your drive (C) called
xampp. See fig 1.2
Steps involved In creating the folder:
Step 2.
Another folder called htdocs will be found inside the
xampp folder. Open the htdocs folder. See fig 1.4

Step 3. Create a new folder inside the htdocs folder and name its crud
2
OPENING FOLDER IN THE WORKING
ENVIRONMENT
Now that we've finished creating our folder, let's examine how we may access it in the working
environment. You've been shown how to set up your environment so that you can begin working.

Assuming you've done that, proceed with the simple instructions below;
1. Open your text editor. See figure below
2. Click on file on the upper left of the editor. See figure below
3. Select open folder in the dropdown list. When you click on it, it will open your pc to
choose your folder. See figures below;
4. Look for the location of the folder. And select the folder and click on the select folder button.
See figure above for the button.
5. When you open the folder successfully, see figure below. You should also see the name of the
folder on the upper left corner of the editor
3
CREATING FILES
Welcome to the next part of our project.
Now that we are done opening our project folder in the working environment (in the text
editor), let us quickly see how to create files in the folder from the working environment.
These files will contain pieces of codes that will come together to form our complete project
Steps involved when creating files:
1. Open your project in the working environment/text-editor. See figure below

Note: refer to chapter 2 of the project if you don’t know how to get the figure above.
2. Right click on the project folder. See figure below;
3. Select and click on New File in the dropdown list. See figure below

4. Click on file and select Save or Save As in the dropdown list to save the file. See
5. After selecting Save or Save As, this is what you are supposed to see. See figure
below;
6. The next step in the process of saving the file is to type the name of the file. You must
type the name plus the extension. Since we are working with php the extension would
be .php. Example: home.php, me.php, update.php. See figure below;
7. After typing the name of the file, just click on the save button and we are done
creating our first file. See figure below after clicking the save button
Exercise:
Now that you know how to create a file, let start by creating all the files for our project. Your
exercise is to open your project folder and create the following files and name them exactly.
I. Config.php
II. Home.php
III. Add.php
IV. Update.php
V. Delete.php
Note: if your project is open already there is no need to reopen it
4
PHP MySQL Database
CREATING DATABASES
AND TABLES
SQL is a standard language used to store, manipulate, and retrieve data from databases.PHP allows
you to connect to and manipulate databases. MySQL is the most often used database system with
PHP

Tables are used to store data in a MySQL database. A table is a collection of linked data that is
divided into columns and rows.
Every table is divided into smaller entities known as fields. StudentID, StudentName, Address,
Telephone, and many other fields can be found in the Student table. A field is a column in a
database that stores special information about each entry in the table.
A record, often known as a row, is each unique entry in a table. A record is a table's horizontal
entity.
A column is a vertical item in a table that holds all of the information related with a given table
field.
What do you do now that you know what a table is?

Steps involved:
1. Launch your Xampp control panel and start
Before Starting

2. Open your browser and type “localhost/phpmyAdmin” in the URL


Note: If you do not write the URL correctly, you may not see what you see in the handout.

This is the MySQL administration interface. This is where we build the database and all of
the tables we'll need. 3. In the admin panel, click the databases or New tab to create a
database.
4. Type the name of the database and click on Create to create the database

When the database is created, it will appear on the left side of the panel.
The name used here is “test”.
STEPS INVOLVED IN CREATING TABLE
1. To create a table, database must be selected. Click on the name of the database
you just created. The name of the database must appear in the URL when selected.
Type the name of the table and specify the number of columns
The number of columns will be determined by the information you collect. Always
include an extra column to capture the principal key. It is expected that you are familiar
with the majority of database-related terminology.

2. After providing the name of the table and setting the number of columns, click on Go.
The last step is to define the names of the individual columns. We are collecting the user's
name, email address, and age in this section. This signifies that the table required three
columns, but we supplied four because the table required a primary key. So the primary
key column, along with the other three columns, equals four. That is why we specified 4
columns.
Note: if the value for the column is an integer, you can decide not to specify the Length,
if it is variable character, the you must specify the Length. A_I stands for Auto Increment;
we want to automatically increase the id field when data is inserted into the table therefore
make sure A_I is checked. Make sure the index field option is also set to PRIMARY since
we want the id field to be the primary key. After setting everything, scroll down and click
on the save button. After clicking on the save button, you will see the image below
INSERTING DATA INTO THE TABLE FROM THE ADMIN SIDE
To insert data into the table;
1. Select the table inside the database; See picture below;
2. Click on the insert button under the server tab; see image below

After clicking on it

3. Enter the values and click on the Go button. Because the id field was set to AUTO
INCREMENT, no value is to be entered there. See image below
After Clicking on the Go button

Now click on browse to see the data


Now that you know how to create a database, how to create a table inside the
database, the main purpose of this handout is to teach you how to use PHP to
manipulate the data in the database i.e. how to add/insert new data, how to delete data,
how to update data and how to read data from the database. Let get started;
5
Data Manipulation
Data manipulation is all about changing data. In this chapter of the handout, I will walk
you through, how to manipulate data in the database with PHP and MySQL. By the end
of this chapter, you should be able to Create, Read, Update and Delete Data from a
database without any difficulties. Let get started with the first part;

Inserting/Adding Data (Create)


In chapter 4, you were taught how to insert data in a database from the admin side of
MySQL. In this part of the tutorial, I will teach you how to Insert/Add/Create data
with PHP without doing that from the admin side. Don’t forget this is the best
practice. Remember, Facebook will not allow any user to go to the admin side of their
Database to add their information. A form will be provided and the user will fill the
form with the required information, then based on the instruction the data is sent to
the database. That is exactly what we are doing here. Ready?

Follow these steps:


1. Open your project folder in the working environment as you were taught in
chapter 3.

2. Create a new file and name it add.php.


3. Create the following files in addition
a. config.php
b. home.php
c. update.php
d. delete.php
Now that all the files have been created, let get started with the home page
What the home page should include;
The data from the database is retrieved and displayed in the home.php file. This file should also
include a link for adding data. There should be a link to update/edit and delete data on each row
of presented data. A example image of the homepage is shown below.

Let open our project in the working environment and see how to code the
image above using HTML. Make sure you select the home.php file, it is there
we are supposed to write the codes for the image above.
Note: It is assumed you know HTML already
home.php file is selected. Let start writing the HTML codes.
Copy the codes below in the home.php file of your project.
Here, we have the basic structure of HTML document.
Note:
➢ Line 1 is telling the type of document we are working with i.e. HTML.
➢ The document is open in line 2 and closed in line 12.
➢ lang= “en” inside the opening of the document is an attribute i.e. language and it is set
to English (en).
➢ The head is opened on line 3 and closed on line 6. The head is giving
some information about the document such as the title of the document.
➢ Inside the head, we have the meta tag with a charset attribute. This is element is
helping us to set the type of characters using with the help of the charset attribute and
the value set to UTF-8. Read more on character set. The title element also set the title of
the document which will appear somewhere in the browser tab.
➢ The body is opened on line 7 and closed on line 11. Whatever you show on the
webpage should be in the body.
➢ The first thing we have to do in our project is to provide a link that will
take us to a page where we can add new data to our database. In this case we have an
anchor element in the body i.e. “a”. The “href” attribute help us to set the file we want to
visit when the link is clicked, in this case we are visiting “add.php” file. The text you
display to visitors to see as a link should be between the opening and closing tag of the
element. In our case “Add New” is what the visitor will see.
➢ To see the result, open your browser and make sure apache and MySQL are up and
running as you were taught in chapter 4. In your browser, type “localhost/the name of
your project folder/the name of the file you want to visit”. In my case, the name of my
project is “crud” and the file I want to visit is “home.php” so I will type

Now when the link is clicked, let see an image for the result. See the image below
You should see a blank page but the name of the file will change based on the value you
provided for the “href” attribute

Add the following codes to your “home.php” file under the anchor element
After Adding the above codes, you should see something like the following ismage
Note: You should refresh your browser before you see this result
Remember “CSS” stylings have been applied here and it is assumed you know this already.
If you want to do same, then add the following styling to your codes.

This type of styling is call internal styling.

Defining an HTML Table


We are using a table to fetch the data from the database into.
An HTML table is defined with the <table> tag.
The table consist of table row (tr), table head (th) and table data (td).
Each table row is defined with the <tr> tag. A table header is defined with the <th> tag. By
default, table headings are bold and centered. A table data/cell is defined with the <td> tag.
Note: Table data (td) element is what contains the actual data.
Now that we have created the table, let see how we can add information to the database and
also fetch the information back to the browser.

CREATING FORMS
The <form> Element
The HTML <form> element defines a form that is used to collect user input
An HTML form contains form elements.
Form elements consist of different types of input elements, such as text
fields, number fields, email fields, submit buttons, and many more
The form <input> Element
The <input> element is the most important form element collecting data from
users.
<input type="text"> defines a single-line input field for text input:
<input type="number"> defines a single-line input field for number input:
<input type="email"> defines a single-line input field for email input:
You can read more about form input on www.w3schools.com.
Now that you have been reminded of how to create forms, open your add.php file and let’s
create a form to take impute from users. Write the following codes in your add.php file

Open your browser and go to the home page of your browser and click on the Add New link
to see the outcome. See image below;
Our mission now is when the form is filled and the add button is clicked, we take all the
information and add to the database.
Before we can communicate with the database, there should be a configuration to be able to
do that. Let then open the config.php file and write the following instructions.
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
PHP script tarts with <?php and ends with ?>
Int the php script above, we start with <?php all the instructions here and end with ?>
To connect to the database, PHP has a built in function called mysqli_connect().
This function takes four (4) parameters.
1. Host name
2. User name
3. Password
4. Database name

Our application is hosted locally using apache localhost


server.
Therefore, the hostname will be “localhost”.
The user name by default is “rood”.
The password by default is “empty” and that is why we
have “”. Do not give space in the quotes.
The name of the database will be the one you have
created.
Note: let it be in order as in the codes.
We finally assign everything to a variable. I
“$connection” here but you can name the way it will make sense
to you.
I use “if statement” to check if the connection is successful.
If the connection is successful, I used PHP built in function
"echo" to output the text "There is connection" on the page:
Now, if you have done exactly then visit your
“config.php” file in your browser and see the outcome.
See image below;

Now that we are able to connect and communicate with the database, let continue and work
on the “add.php” file
Note: Any file that will communicate with the database must
include the database.
In the “add.php” file, since there will be a communication
with database, the “config.php” must be included in the
“add.php”.
In PHP, to include a file in another file, we use a built-in
function called “include”.
The file you want to include must appear at the of the file
where you are including it.
See image below;

Now
when we visit the “add.php” file in the browser we
should see whatever we “echo” in the “config.php” file. See
image below;
We have visited the “add.php” file but see the test the yellow
arrow is pointing to; it is coming from the “config.php” file.
Now what it means is that we can use the connection variable
and talk to the database when inserting/adding anything to the
database.
Note: since we are connected to the database, there is no need
to “echo” something. Therefore, remove the text “There is
connection” from the “config.php”.
After removing the text, see image below;
Let continue with the “add.php” file;
Open another PHP tag right below the closing tag of where
we included the “config.php” file. Copy the following codes
and let see what they do and the result.
Two main Methods of Submitting a form
1. POST
2. GET
When a form is submitted, PHP uses one of the two
methods to collect the form data. The method is
specified in the “method= “” ” attribute in the
opening form tag. If not specified, by default the
method would “get”. We have used a post method
here to collect the form data.
Note: You would be taught in the theory aspect of this
cause these methods.
When collecting form data with PHP, php use the value of
the name attribute given to the input field.
In the codes above,
1. Line 6 uses an “if” statement and a built-in function in
php called “isset” to check if the is clicked. The method
used is “post” and the name of the button is “add”. To
access the value of the input field, php uses a built-in
super global variable “$_POST[“”]” and the name of the
field is passed on to the variable. In this case we have
$_POST[“add”] since the name of the button is “add” to
check if the button is clicked.
2. If the button is clicked, on line 8, we have assigned a
variable to access the name.
3. If the button is clicked, on line 9, we have assigned a
variable to access the email.

4. Lastly, if the button is clicked, we have assigned a


variable to access the age.
Now, let’s use the “echo” function to echo the name,
email and age if the button is click.
Now, visit the “add.php” file in your browser, enter your
name, email and age and click on the “ADD” button. See
image below for result;
AFTER
We have seen that when we fill the form and click on the
“ADD”, we are able to fetch the information with PHP and
output the information in the browser.
Since we are able to fetch the information, let use PHP to
insert/add into the database.
Note: remove the “echo” from the codes. We are not outputting
in the browser.
See update of the codes when the “echo” is removed;
To insert/add the information in the database, we have to write
PHP instructions to do that.
PHP has a built-in function called “mysqli_query”.
This function takes two parameters.
The first parameter is the “connection variable”.
The second parameter is the “MySQL query”.
Note: It is assumed that you have the basics of database
queries.
Copy the following codes and add to your “add.php”. See
codes below;
After copying the above codes, save and view the “add.php”
in the browser.
Fill the form and click on the “ADD” button.
When the button is clicked, you do not see anything.
If you did everything right, then the information would be
inserted/added to the database.
To see what is happening, let assign a variable to the codes on
line 12 above

Since we have assigned a variable to the query, we can now


use the variable to check if the insertion was successful. See
codes below and add to your file;
II
Fetching Data
(Read)
Now that you know how to add data to the database, in this part of the tutorial, I will
teach you how to fetch/read the data that you have added to the database for users to
see in the homepage of your application.
Have you ever wondered how Facebook print your name, date of birth, age, gender,
telephone and other information in your profile page of your Facebook account? Stay
focus and I will teach the same thing here. Let get started;
Open your project folder in your text editor and open your “home.php” file

Our focus will be on the table that was created when the homepage was created. The
data will be read into the table
When you take note of the table, you could realize that it has two rows

Inside Row 1 we have the table headings.


Inside Row 2 we have the actual table data.
Row 1 will always remain the same because each column in a row must have a heading.
When the data is read from the database, Row 2 will keep changing based on the number of
Rows we have in the table from the database.
Since Row 2 will be changing, it is a must for us to use a “loop statement” to loop through
the table in the database and get all the data. You will learn “loops” in the theory part of this
tutorials. Therefore, it is assumed that you what “loops” are in PHP. In this tutorial, I will use
“while loop” to display the all the data that will come from the table in the database. Let
continue;
Copy the codes below into your “home.php” file.

ine 36 starts PHP and line 44 is ending PHP before the table row start.
Line 37 is getting the data in the users table with the help of “mysqli_query” PHP function to
get data from database. This function is taking two parameters, first the connection variable
and second, the “SQL” statement to get the information from the users table. I then assign the
result to “$get_users” variable. This “$get_users” variable is now holding all the data from the
users table.
I now use PHP “while loop” to loop through the results in the “$get_users” variable in line 39.
To be able to display the information, we have to get the column headings in the users table.
PHP uses and “array” of which you should know before working on this project in the theory
part of this tutorials to put all the column names. Here, I have used “mysqli_fetch_array”
function to get the column names and reassign to a variable called “$row” which also becomes
an array. This array variable will hold the column names from the table. For example, to get the
name from the table, because the “$row” variable is holding the column names, “$row[‘name’]”
will give us all the names from the “name” column, “$row[‘email’]” will give us all emails from
the email column and so on 66.
If the table contains more than one row, using “while loop” will give all the data, and that is
exactly what I have done.
Note: The row must be in the “while loop”. That is why on line 53, PHP is started and
ended on the same line with the closing curly bracket (}) of the “while loop” in between.
This is telling us where the loop has ended.

If everything has been done correctly, you add new user and visit the “home.php” file and
you should see similar result like this below;
I have two results displaying because there are two rows in the users table. See figure below;

Compare the results

PHP CRUD PART 2


(HOW TO DELETE AND UPDATE)
In this tutorial we shall learn how to delete and update (Edit) data from php MySQL database.
LET GET STARTED
STEP 1
Create the update (Edit) and delete Files inside your working Folder as show below.
STEP 2
THE NEXT THING TO THINK ABOUT IS THE SQL SELECT STATEMENT.
INSERT THE CODES BELOW INTO YOUR edit.php file.
$sql="select * from users_data where UID='{$_GET["id"]}'";
$res=$con->query($sql);
if($res->num_rows>0){
$row=$res->fetch_assoc();

Make sure u select from the table in your database. In my case the table I created is users_data.

STEP 3
Because we want to edit an existing database file, the next step is to copy and paste your form into
the edit.php file as show below;
THE CODES IMAGE IS SHOWN BELOW
STEP 4
ENSURE THAT YOU BREAK YOUR STATEMENT AS DEMONSTRATED BELOW.
BREAK

The break keyword is used to break out the loop.

STEP 5
Make sure your configuration file is included in your edit.php file.
Your database connectivity is included in the config.php file.
Ascertain that the session has begun.
<?php
session_start();
include "config.php";
?>
STEP 6
Finally, ensure that the "id" is present in your table data under the table body, as shown below.

You Can Copy the codes below into your edit.php file
<?php
session_start();
include "config.php";

#Check if form submitted


$message="";
if($_SERVER["REQUEST_METHOD"]=='POST'){
$name=mysqli_real_escape_string($con,$_POST["frm_name"]);
$email=mysqli_real_escape_string($con,$_POST["frm_email"]);
$contact=mysqli_real_escape_string($con,$_POST["frm_contact"]);
$sql="UPDATE users_data SET
NAME='{$name}',EMAIL='{$email}',CONTACT='{$contact}' WHERE
UID='{$_GET["id"]}'";
if($con->query($sql)){
flash('msg','User Updated Successfully');
}else{
flash('msg','User Updated Failed','red');
}
}

#Select user details from the table


$sql="select * from users_data where UID='{$_GET["id"]}'";
$res=$con->query($sql);
if($res->num_rows>0){
$row=$res->fetch_assoc();
?>
<html>
<head>
<title>PHP - MySQL CRUD </title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<div class='container'>
<?php flash('msg'); ?>
<form method='post' action='<?php echo
$_SERVER["REQUEST_URI"]; ?>' class='frm'>
<h1>PHP - MySQL CRUD</h1><hr>
<div class='group'>
<label>Name : </label>
<input type='text' name='frm_name' required
value="<?php echo $row["NAME"]; ?>">
</div>
<div class='group'>
<label>Email : </label>
<input type='email' name='frm_email' required
value="<?php echo $row["EMAIL"]; ?>">
</div>
<div class='group'>
<label>Contact : </label>
<input type='text' name='frm_contact' required
value="<?php echo $row["CONTACT"]; ?>">
</div>
<div class='group'>
<input type='submit' name='submit' class='btn-
green' value='Update Details'>
</div>
<a href='index.php'>Back to Home</a>
</form>
</div>
<?php
}
?>
</body>
</html>

The final result is shown below;


BEFORE UPDATE (EDIT)
AFTER UPDATE(EDIT)
DELETING DATA FROM TABLE
GO TO YOUR DELETE FILE INSIDE YOUR WORKING FOLDER AND PASTE THE
CODES BELOW.
In my case the name of my table is users_data
<?php
//Delete php codes
session_start();
include "connect. Php";

$sql="DELETE FROM users_data WHERE SID='{$_GET["id"]}'";

$result = mysqli_query($connection,$sql);
if ($result) {
echo "user deleted successfully";

else{
echo "User Deleted Failed";
}
?>

Note
Include the “id” in the table body as show below

BEFORE DELETE
AFTER DELETE

You might also like