Lecture 8 Notes
Lecture 8 Notes
Lecture 8 Notes
Development
Lecture 8
▪ Insert data into the database and manipulate any data in the database.
Introduction
The power of server-side scripting languages is in their capability to create dynamic,
database driven application. Such applications give room for free flow of data into and out
of the database. To implement this functionality, server-side scripts like PHP must be
execute SQL statements categorized as Data Manipulation Languages (DMLs). These
statements provide mechanisms for inserting, updating, selecting, and deleting data. This
topic will explore how PHP can execute DMLs for inserting and manipulating data in the
database. To achieve these, the first step entails creating a database and tables that will
hold the data. The topic will hence cover the process for creating the two.
Creating Databases and Tables Using phpMyAdmin
Creating databases and tables can be achieved in two different ways. The first approach that
is best suited for many users is using the phpMyAdmin web application. The second
approach entails executing SQL statements via PHP scripts. This section covers the first
approach.
As earlier introduced in previous topics, it is important to ensure that the XAMPP Control
Panel icon is running with Apache and MySQL services running as shown in Figure 1. This
may be on the system tray.
Figure 1. Apache and MySQL Services Running
The next step is to be familiar with the MySQL database, how to create a database and
tables even before we get to PHP scripts for interacting with the database engine. Part of
the XAMPP package is the phpMyAdmin, a web application used to manage the database
engine in XAMPP.
The phpMyAdmin web application can be opened and used through the browser. Start by
opening http://localhost to access the interface shown in Figure 2.
Figure 2. Opening the Webserver from the Browser (Using http://localhost)
Part of the main menu items is a link to the phpMyAdmin application. Clicking on it to get to
the phpMyAdmin interface shown in Figure 3.
For the sake of this topic, we will create a database called “University” and a table called
“Students”. The table will have four fields, namely, AdmNo, Name, Age, Program. The
admno represents the student admission number which will act as the primary key in this
table. From the phpMyAdmin web interface, we start by creating the database by clicking
on the Databases tab, specify the database name then clicking create as outlined in Figure 4.
Figure 4. Interface for Creating a Database in phpMyAdmin
Upon clicking the create button, the database gets created and ready for creation of tables.
You end up being redirected to the following interface that will allow you to specify a table
name and desired number of columns to define the table as shown in Figure 5.
For the sake of this topic, we will set the table name to “Students” with 4 columns then click
the Go button to proceed. This lands you on the following interface that requires you to
specify the four column names and their properties. This is as shown in Figure 6.
Figure 6. Interface for Specifying Table Field and their Properties in phpMyAdmin
Set the column names as indicated in the interface in Figure 6. Be sure to set the index for
AdmNo to primary. This will make the field to act as the primary key for the table. Click the
Save button to effect table creation. This will land you to the interface shown in Figure 7.
Up to this point, the database and table are ready for use. Any changes or modification can
be performed with ease from the phpMyAdmin GUI. For the sake of this topic, all is set for
us to proceed to writing PHP scripts to connect to the database and insert and manipulate
data in the database table.
The same task of creating databases and tables described above can be achieved through
writing and executing SQL statements through the query browser that comes as part of the
phpMyAdmin web application. The query browser can be opened by clicking the SQL tab on
the main menu for the phpMyAdmin web interface.
The query browser option is used by user that are good in writing and executing SQL
queries. Upon writing any valid SQL query, clicking on the Go button at the bottom right end
of the interface triggers execution of the query.
Removing Databases and Tables Using phpMyAdmin
To remove a database, you can use the operations tab with the database or table selected.
A link leading to the removal process will appear on the interface. Following the link opens a
confirmation prompt with the OK button finishing the operation. It is worth noting that the
processing of removing a database or table is called dropping. Figure 9 to 12 show the steps
for dropping the table and database that we created in the previous subsection.
Figure 9. Opening the Operation Tab with Table Students Selected
Figure 10. Confirmation Prompt Upon Following the Delete Table Link
Figure 11. Opening the Operation Tab with Database University Selected
Figure 12. Confirmation Prompt Upon Following the Drop Database Link
The same can be achieved by executing the following SQL statements in the query browser
of the phpMyAdmin.
drop table Students;
drop database University;
Creating Databases and Tables Using PHP Scripts
PHP provides a mysqli_query() function for executing SQL queries. The mysqli_query()
function is the workhorse of PHP connectivity with MySQL with almost every SQL query
send to MySQL from PHP scripts being executed by the function [2]. Such queries may be
used to accomplish any task including creating and removing databases and their objects,
inserting, updating, retrieving, removing data for the database. The mysqli_query() function
takes two parameters, namely, the database connection string and a valid SQL query. It
returns a Boolean value TRUE or FALSE depending on the outcome of the execution of the
SQL query. This is the case only for SQL statements that do not return information from the
database. In cases of statements that return information from the database like the select
statement, the function returns a result pointer that represents query results [2]. This will
be explained in detail in the next topic. As earlier discussed, the “or die()” function can be
appended to the mysqli_query() function to capture and report instances the SQL query fails
to execute. The if … else statement could still be applicable in this case to achieve the same
functionality.
Syntax
mysqli_query(connection_string, sql_query);
Replacing the sql_query parameter with any valid SQL statement will see the statement
executed upon execution of the function. For instance, to create a database called
University, the SQL statement “create database University” should be provided as the
sql_query parameter. The function must come after the function for establishing a
connection to the database has been defined in the PHP script and tested to ensure that it is
connecting successfully to the MySQL database server.
Example
The following PHP script creates a database called University.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
Notice the fact that the first part of the script establishes a connection to the database
server. This has been applied as covered in the last topic. The connection string assigned to
variable $connect has been supplied as the first parameter in the mysqli_query() function.
Once a database has been created, it is now ready for use. Such a database must be
selected to make it active in any PHP script that desires to utilize it. This is achieved using
the mysqli_select_db() function. The function returns a Boolean value TRUE or FALSE upon
execution.
Syntax
mysqli_select_db(connection_string, database_name);
Example
The following example establishes a connection to the MySQL database server, then selects
a database called “University” for use within the script.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
The “or die()” function appended to the mysqli_query() function helps to capture and report
attempts to access databases that do not exist. From this point onwards, any SQL statement
executed will affect database “University” that is active for use within the script.
To create a table in a database, the following syntax should inform the structure of SQL
statements that should be supplied as sql_query parameters.
For instance, to create a table called Students, the SQL statement “create table Students
(AdmNo int, Name varchar(20), Age int, Program varchar(50), primary key(AdmNo))” should
be provided as the sql_query parameter. The function must come after the function for
selecting the database called “University” has been defined in the PHP script. This is as
shown in the following example.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
Similarly, the “drop table table_name” SQL statement syntax is used to remove a table from
a database, where table_name represents the name of an existing table in a database. For
instance, to remove a table called Students from the University database, the SQL statement
“drop table Students” should be provided as the sql_query parameter for the
mysqli_query() function. The function must come after the function for selecting the
database called University has been defined in the PHP script. This is as shown in the
following example.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
For instance, to insert a sample record into the Students table, the SQL statement “insert
into Students (AdmNo, Name, Age, Program) values (100, ‘John Doe’, 20, ‘Computer
Science’)” should be provided as the sql_query parameter. The function must come after
the function for selecting the database called “University” has been defined in the PHP
script. This is as shown in the following example.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
The following HTML code creates a form that could be used to capture students details to
be stored in the Students tables.
<!doctype html5>
<html>
<head>
<title>Students Details</title>
</head>
<body>
<form method="POST" action="processformdata.php">
Admission Number <input type="text" name="admno" /><br />
Student Name <input type="text" name="name" /><br />
Age <input type="text" name="age"><br />
Program <input type="text" name="program" /><br />
<input type="submit" value="Add Student" />
<input type="reset" value="Refresh" />
</form>
</body>
</html>
The following PHP script saved as "processformdata.php" will be used to receive form data,
process the data, then send it to the database.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
//update the program for John Doe from Computer Science to Education
mysqli_query($connect, "update Students set Program='Education' where
Name='John Doe'") or die("Could not update the data in the database");
Using the same approach, SQL statements to remove data (records) from the database can
be executed. The syntax for such statements is as follows.
Delete from table_name where condition;
The WHERE clause in the delete statement applies in a similar manner as described for the
update statement. It is worth mentioning that the WHERE clause works the same across any
SQL statement. For instance, suppose we want to remove the record for John Doe from the
database, we would need to execute a PHP script containing the following delete SQL
statement with the WHERE clause focusing on the name of the student.
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}else{
echo "Connection to the database engine successful";
}
Summary
The topic has explored critical aspects of executing SQL statements using PHP. The
statements covered so far were limited to creating and removing databases and tables,
inserting and manipulating data in the database and deleting data from the database. A
number of functions have been introduced including the mysqli_select_db(), mysqli_query(),
mysqli_error() and mysqli_errno() functions. The mysqli_query() functions dominates as the
main function for executing relatively all valid SQL statements supplied to it.
Check Points
1. Describe the process of creating and removing databases and tables using phpMyAdmin.
2. Demonstrate the process of creating and removing databases and tables using PHP
scripts.
3. Demonstrate how form data can be inserted in the database.
4. Demonstrate how data in the database can be manipulated or records removed.
5. Describe the process of error reporting in PHP-MySQL scripting.
Learning Resources
Core Textbooks
Other Resources
3. https://www.w3schools.com/php/DEFAULT.asp
4. https://www.tutorialspoint.com/php/index.htm
References
[1] Brooks, D.R., 2017. Programming in HTML and PHP. Switzerland: Springer.
[2] Gosselin, D., Kokoska, D. and Easterbrooks, R., 2010. PHP Programming with MySQL:
The Web Technologies Series. Cengage Learning.