UNITY UNIVERSITY
Department of Computer Science
Addis Ababa, Ethiopia
Contents
• Introduction
• Connect to Database
• Send Data to a Database
• Retrieve Data from a Database
• Modify Existing Data
• Remove Existing Data
• Data base security using server side scripting
Introduction
• A database has usually its own software, the Data Base Management
System, which operates on the data.
• The most popular database used in connection with PHP is MySQL,
which is open source and free software.
• Commercial database software frequently used with PHP is POSTGRESS,
ORACLE and SyBASE. All these database systems require separate
installation
• MySQL is a freely available open source Relational Database Management
System (RDBMS) that uses Structured Query Language (SQL).
– SQL is the most popular language for adding, accessing and managing
content in a database.
– It is most noted for its quick processing, proven reliability, ease and flexibility
of use.
... Introduction
• PHP is a server-side scripting language designed specifically for the Web.
• MySQL is a very fast, robust, relational database management system (RDBMS).
• A database enables you to efficiently store, search, sort, and retrieve data.
• One of the best features of both PHP and MySQL is that they work with any
major operating system and many of the minor ones.
• Connecting MySQL database with php web applications is the focus of this chapter
• There is GUI tools to manage MySQL database.
• phpmyadmin is the most commonly used tool which is used in this course.
... Introduction
• phpmyadmin is a free browser-based tool for MySQL administration.
• phpMyAdmin is one of the most popular applications for MySQL database
management.
• Through this software you can
– Create
– Alter
– Drop
– Delete
– import and export MySQL database tables.
• You can run MySQL queries, optimize, repair and check tables, change collation
and execute other database management commands.
• You can access phpMyAdmin by writing http://localhost/phpmyadmin/ in
the RUL which displays the following interface
... Introduction
Phpmyadmin feature are:
•Intuitive web interface
• Support for most MySQL features:
– browse and drop databases, tables, views, fields and indexes
– create, copy, drop, rename and alter databases, tables, fields and indexes
– maintenance server, databases and tables, with proposals on server configuration
– execute, edit and bookmark any SQL-statement, even batch-queries
– manage stored procedures and triggers
• Import data from CSV and SQL
• Export data to various formats:
– CSV, SQL, XML, PDF, ISO/IEC 26300
– OpenDocument Text and Spreadsheet,Word, LATEX and others
• Creating complex queries using Query-by-example (QBE)
• Searching globally in a database or a subset of it
• Transforming stored data into any format using a set of predefined functions, like
displaying BLOB-data as image or download-link
... Introduction
Generally:
• PHP is particularly strong in its ability to interact with databases. And it supports
pretty much every database out there. However, the most commonly used
database with PHP is MySQL
• MySQL is a free and open source database that has a lot of users especially for
web applications.
• Whichever database you’re using, the steps to interact with a database are similar:
1. Creating database
2. Connect to the database.
3. Send an SQL query that contains instructions for the database
software.
4. If you retrieved data from the database, process the data.
5. Close the connection to the database.
Creating Database using phpMyAdmin
• Before saving or accessing the data, we need to create a database first.
For this purpose we can use phpMyAdmin or php itself
• Steps in phpMyAdmin:
– Open your favourite browser
– Write http://localhost/phpmyadmin/ in the URL
– It automatically displays the phpMyAdmin home page
– Click on database from the navigations
• It provides space to enter database name
• Below it there is already created databases
– Type the name of the database (assosacity) and click on create
• After creating your database, the name of the database will be displayed
in the database list (to the left side).
• Now you can create tables inside it.
• See the next slides to create database . . .
Creating Database . . . Cont.
Creating Database . . . Cont.
Creating Database . . . Cont.
Connect to an existing Database
• Now you have created database called assosacity, the next step is . . .
• Create connection: the function to connect to MySQL is called mysql_connect
which Open a connection to a MySQL Server in php 4&5.
• But this extension was deprecated in PHP 5.5.0, and it was removed in PHP
7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
• The PHP's MySQLi extension provides both speed and feature benefits over the
PDO extension, so it could be a better choice for MySQL-specific projects.
• In PHP you can easily Connecting to MySQL Database Server using the
mysqli_connect() function.
• All communication between PHP and the MySQL database server takes place
through this connection
• Syntax:
$link = mysqli_connect("hostname", "username", "password", "database");
Connect to an existing Database . . . Cont.
• The hostname parameter in the above syntax specify the host name (e.g.
localhost), or IP address of the MySQL server,
• whereas the username and password parameters specifies the credentials to
access MySQL server, and
• the database parameter, if provided will specify the default MySQL database to
be used when performing queries.
• The default username for MySQL database server is root and there is no
password.
• However to prevent your databases from intrusion and unauthorized access you
should set password for MySQL accounts.
• The connection to the MySQL database server will be closed automatically as
soon as the execution of the script ends.
• However, if you want to close it earlier you can do this by simply calling the PHP
mysqli_close() function. It contains the connection as parameter.
Connect to an existing Database . . . Cont.
• The mysqli_connect_error() function returns the error description from the last
connection error, if any
• The mysqli_close() function closes a previously opened database connection.
Creating Database using php
• Now that you have understood how to open a connection to the MySQL database
server.
• The next step is to create a database using php to save or access data.
• The CREATE DATABASE statement is used to create a new database in MySQL.
• Steps:
– Make a SQL query using the CREATE DATABASE statement,
– execute this SQL query by passing it to the PHP mysqli_query() function
– finally it will create the database.
– The following example creates a database named student.
– Note that the connection is already created, in this example $connection
$query=“CREATE DATABASE student”;
$db=mysqli_query ($connection, $query);
Creating Database . . . Cont.
Selecting database
RDBMS can create and maintain many databases, so you need to tell it which
database you want to use.
• The mysqli_select_db() function is used to change the default database for the
connection. Syntax: mysqli_select_db(connection,dbname);
• For the previous database that is created (assosacity)
selecting database . . . Cont.
Creating Tables inside MySQL Database using PHP
• In the previous slides we have seen how to create a database on MySQL server.
• Now create some tables inside the database that will actually hold the data.
• A table organizes the information into rows and columns.
• The SQL CREATE TABLE statement is used to create a table in database.
• Steps:
– Make a SQL query using the CREATE TABLE statement
– Syntax
– execute this SQL query by passing it to the PHP mysqli_query() function
– finally it will create the table.
– The following example creates a table named resident inside assosacity database.
– Note that the connection is already created, in this example $connection
Creating Tables . . . Cont.
• Each column name is followed by a data type declaration; this declaration
specifies that what type of data the column will store, whether integer,
string, date, etc.
Creating Tables . . . Cont.
• There are a few constraints (also called modifiers) that are set for the table
columns in the preceding statement.
• Constraints define rules regarding the values allowed in columns.
Creating Tables . . . Cont.
Creating Tables . . . Cont.
• Alternatively, you can create tables inside database using phpMyAdmin
• First select the database from the left side, type the name of your table, specify the
number of columns and click Go
Creating Tables . . . Cont.
Creating Tables . . . Cont.
• At the bottom, there is save option
• Save you table by clicking on Save
Send Data to a Database
• Now you have open the connection and you have select the working database.
• The next step is Send an SQL query that contains instructions for the
database software.
• The mysqli_query() function performs a query against the database.
• Syntax: mysqli_query (connection, query);
– connection (Required): Specifies the MySQL connection to use
– query (Required): Specifies the query string
• First you need to create a table inside the database assosacity, for this
example we have created table called resident which contains information
about Assosa city people.
• Basic steps:
– make a connection,
– send a query, and
– check the results.
• In this case, the query you send will be an INSERT.
• The following slide shows some of the basic queries . . .
Send Data to a Database . . . Cont.
Send Data to a Database . . . Cont.
Inserting Data into a MySQL Database Table (3ways)
• 1) using INSERT INTO statement which is used to insert new rows in a database
table.
– make a SQL query using the INSERT INTO statement with appropriate values,
– execute this insert query by passing it to the PHP mysqli_query() function to insert
data in table.
– Example: insert a new row to the resident table by specifying values for the
first_name, middle_name, last_name, age, email, gender and description fields.
• You can insert data into tables by accepting the data from the user by
providing UI or form. (will be discussed in next topic)
– For example if there is a registration form, the user fills the form and submits the data,
after some process like validation of user input, the data will be inserted to the
database
• You can also insert data into tables using phpMyAdmin Interface
Send Data to a Database . . . Cont.
Insert Data into a Database from an HTML Form
• In the previous slide, you have seen how to insert data into database from a PHP
script.
• 2) Now, we'll see how we can insert data into database obtained from an HTML
form.
• Steps:
– Create an HTML form that can be used to insert new records to resident table.
– Retrieving the Form Data (validating it)
– Inserting the Form Data
• Note: The mysqli_real_escape_string() function escapes special characters in a
string and create a legal SQL string to provide security against SQL injection.
– SQL injection is an attack wherein an attacker can inject or execute malicious SQL
code via the input data from the browser to the application server, such as web-form
input.
Insert Data From an HTML Form . . . Cont.
Insert Data From an HTML Form . . . Cont.
Insert Data From an HTML Form . . . Cont.
• More examples
– including outputs of the previous insert php code
–Inserting data from form
–Inserting media files (documents, image, video, etc.)
will be elaborated during Lab classes
Insert Data From an HTML Form . . . Cont.
• Adding profile picture and registration date in resident table
– So two columns must be included in our table after description
• photo
• registration_date
– Go to phpMyAdminselect assosacity database
– click on resident tablego to sturacture
– add 2colums after description and click GO
• Also, the registration form created before must be modified to add
option for the user to upload their photo.
• In addition, the form must contain hidden field and enctype attribute as
multipart/form-data
Insert Data From an HTML Form . . . Cont.
• Adding profile picture and registration date in resident table
• Complete PHP Code
Insert Data From an HTML Form . . . Cont.
• Assume, you have ‘uploaded’ folder inside in your working directory, and
then ‘images’ folder inside ‘uploaded’ which contain all profile photos
Insert Data From an HTML Form . . . Cont.
• Now, execute the usual query to insert data from form which is explained
in the previous topic
• Just add $photo in the photo column filed and
• Add $registered_date in the registered_date field
• The registered_date looks like:
• To check complete and successful photo and registered date insertion,
Attend @lecture and Lab class ……………………
Retrieve Data from a Database
• In the previous slides, you have learnt how to create database and table as well as
inserting data. Now it's time to retrieve data what have inserted
• The SELECT statement is used to select or retrieve the data from one or more
tables.
• You can use this statement to retrieve all the rows from a table in one go, as well
as to retrieve only those rows that satisfy a certain condition or a
combination of conditions.
• Its basic syntax is as follows:
SELECT col1_name, col2_name, colN_name FROM table_name;
– Here, col1_name, col2_name, ... are the names of the columns or fields of a
database table whose values you want to fetch.
– However, if you want to fetch the values of all the columns available in a table:
SELECT * FROM table_name;
The asterisk (*) is a wildcard character that means everything.
Retrieve Data . . . Cont.
• Steps: 1. make a SQL query using the SELECT statement
2. execute this SQL query by passing it to the PHP mysqli_query() function to
retrieve the table data.
Retrieve Data . . . Cont.
• Select all records and display inside table (create an HTML table)
Retrieve Data . . . Cont.
. . . Explanation
• In the previous example, the data returned by the mysqli_query() function is
stored in the $result variable.
• Each time mysqli_fetch_array() is invoked, it returns the next row from the
result set as an array.
• The while loop is used to loops through all the rows in the result set.
• Finally the value of individual field can be accessed from the row either by
passing the field index or field name to the $row variable like $row['id'] or
$row[0], $row['first_name'] or $row[1] etc.
• mysqli_free_result () function frees the memory associated with the result.
Retrieve Data . . . Cont.
Selecting Record Based on Condition
• In the previous slides, you have seen how to fetch all the records form a table or
table columns.
• But, in real world scenario we generally need to select, update or delete only
those records which fulfil certain condition like users who belongs to a certain
age group, or email, salary, etc.
• The WHERE clause is used for this purpose and it works with the SELECT,
UPDATE, and DELETE.
• The WHERE clause is used with SELECT statement to extract only those
records that fulfil specified conditions.
Retrieve Data . . . Cont.
Syntax in SELECT statement
SELECT column_list FROM table_name WHERE condition(s);
• Here, column_list are the names of columns/fields like name, age, email etc. of a
database table whose values you want to fetch.
• However, if you want to fetch the values of all the columns available in a table,
you can use the following syntax:
SELECT * FROM table_name WHERE condition(s);
• The following SQL statement will returns all the people from the resident table,
whose age is less than 18.
• The WHERE clause simply filtered out the unwanted data.
Retrieve Data . . . Cont.
• The complete code to retrieve only first name and email from resident table
Retrieve Data . . . Cont.
• Operators Allowed in WHERE Clause
Retrieve Data . . . Cont.
Retrieve Data . . . Cont.
Some of MySQL functions that are used during data retrieval
Retrieve Data . . . Cont.
• Selecting Record Based on Condition using AND & OR
• Example to retrieve a person where age less than 18 and gender is female from
resident table:
• Using AND
• Result (See Age and Gender column)
– It returns true result, only if both (age, gender)are matched
Retrieve Data . . . Cont.
• Using OR
• Result (See Age and Gender Column)
– If one of the condition is matched (age, gender), it returns true result
Retrieve Data . . . Cont.
Selecting Record Based on Condition using LIKE and NOT LIKE
• Using numbers, dates, and NULLs in conditionals is a straightforward process, but
strings can be trickier.
• You can check for string equality with a query such as:
SELECT * FROM resident WHERE first_name = ‘Haile‘;
• However, comparing strings in a more liberal manner requires extra operators
and characters.
• If, for example, you wanted to match a person’s first name that could be Nigat or
Nigatu or Nigatnesh, you would need a more flexible conditional.
• This is where the LIKE and NOT LIKE terms come in.
• These are used primarily with strings in conjunction with two wildcard characters:
– the underscore ( _ ), which matches a single character, and
– the percentage sign (%), which matches zero or more characters
Retrieve Data . . . Cont.
. . . Continued
SELECT first_name, email FROM resident WHERE first_name = ‘Nigat%‘;
• This query will return all rows whose first_name value begins with Nigat.
• Because it’s a case-insensitive search by default, it would also apply to names that
begin with nigat
• Example:
– Select the first name and email for every record whose age is less than 18 and email
address is not of the form [email protected]
Retrieve Data . . . Cont.
Sorting Query Results
• By default, a SELECT query’s results will be returned in a meaningless order (for
many new to databases, this is an odd concept).
• To give a meaningful order to a query’s results, use an ORDER BY clause:
SELECT * FROM tablename ORDER BY column
SELECT * FROM resident ORDER BY first_name
• The default order when using ORDER BY is ascending (abbreviated ASC),
meaning that;
– numbers increase from small to large,
– dates go from oldest to most recent, and
– text is sorted alphabetically.
• You can reverse this by specifying a descending order (abbreviated DESC)
SELECT * FROM tablename ORDER BY column DESC
Retrieve Data . . . Cont.
. . . Continued
• You can even order the returned values by multiple columns:
SELECT * FROM tablename ORDER BY column1, column2
• You can, and frequently will, use ORDER BY with WHERE or other clauses.
When doing so, place the ORDER BY after the conditions:
SELECT * FROM tablename WHERE conditions ORDER BY column
Retrieve Data . . . Cont.
Limiting Query Results or data selection using LIMIT
• Another SQL clause that can be added to most queries is LIMIT. In a SELECT
query, WHERE dictates which records to return, and ORDER BY decides how
those records are sorted, but LIMIT states how many records to return.
• It is very useful on large tables because returning a large number of records can
impact on performance.
• Syntax:
SELECT * FROM tablename LIMIT x
• In such queries, only the initial x records from the query result will be returned.
• To return only three matching records, use:
SELECT * FROM tablename LIMIT 3 Using this format to select 3 records
SELECT * FROM tablename LIMIT row_offset, row_count;
• you can have y records returned, starting at x.
Retrieve Data . . . Cont.
. . . Continued
• To have records 11 through 20 returned, you would write
SELECT * FROM tablename LIMIT 10, 10
• Like arrays in PHP, result sets begin at 0 when it comes to LIMITs, so 10 is the
11th record.
• Because SELECT does not return results in any meaningful order, you almost
always want to apply an ORDER BY clause when using LIMIT.
• You can use LIMIT with WHERE and/or ORDER BY clauses, always placing
LIMIT last:
SELECT which_columns FROM tablename
WHERE conditions ORDER BY column LIMIT x
• See examples in next slides and at Lab class
Pagination/Paging in PHP
• It’s always possible that your SQL SELECT statement query may result into
thousands of records.
• But it is not good idea to display all the results on one page.
• So we can divide this result into many pages as per requirement.
• Pagination means showing your query result in multiple pages instead of just put
them all in one long page.
• MySQL helps to generate paging by using LIMIT clause which will take two
arguments.
– First argument as OFFSET and
– second argument how many records should be returned from the database.
• The following slide shows simple example to fetch 5 records from resident table
using LIMIT clause to generate pagination.
Pagination/Paging in PHP . . . Cont.
• The example displays 5 records per page
– So, if there is 16records, there will be 3pages
– To access second and third page of data, there will be NEXT clickable link
– To access second and first page of data, there is PREVIOUS clickable link
– If the page is at first page, PREVIOUS is not used as link
– If the page is at last page, NEXT is not used as link
– Otherwise both are used as link (Note: you can beatify your table using CSS)
Pagination/Paging in PHP . . . Cont.
The Complete PHP Code
Pagination/Paging in PHP . . . Cont.
. . . Continued (1)
Pagination/Paging in PHP . . . Cont.
. . . Continued (2)
. . . Continued
Pagination/Paging in PHP . . . Cont.
. . . Continued (4)
Searching Existing Data
• Developing a robust, interactive and engaging Web site involves many different
avenues, such as
– interactive pop-out menu’s using
• dynamic JavaScript,
• Cascading Style Sheets (CSS),
• complex maps that allows visitors to rollover individual sections for detailed information,
forms designed and formatted with CSS and are programmed to collect and send visitor
feedback to a specified recipient.
• Without question, one of the most popular features of any database driven site is a
searchable form feature that allows
– anyone to search for current events of an organization and
– find additional information, such as email address or phone number of employees.
• Now, in next slide, we will see how to search resident information from resident
table (Search by id, name or E-mail)
Searching Existing Data . . . Cont.
• Steps:
– First create the search FORM
• It contains three options (ID, Name and E-mail)
– Receive the input data from the form
• If the user click on Search button without typing search word, inform them to enter search
keyword
– Based on the received input, display the searched information for users
• Look the following slide
– which contains all the records inside resident table
• Search and display some data from this table
Searching Existing Data . . . Cont.
• Attend @Lab class for php and MySQL code to do the
previous tasks
• Example:
–Search by Id
–Search by Name
–Search by E-mail
Refer Lab Materials !
Modify Existing Data
• The UPDATE statement is used to change or modify the existing records in a
database table.
• This statement is typically used in conjugation with the WHERE clause to apply
the changes to only those records that matches specific criteria.
• Syntax:
UPDATE table_name SET column1=value, column2=value2,... WHERE
column_name=some_value
• Example: modify the email address of a person in the resident table whose id is
equal to 19.
Modify Existing Data . . . Cont.
Refer Lab Materials !
Remove Existing Data
• Just as you insert records into tables, you can remove records from a table using
the SQL DELETE statement.
• It is typically used in conjugation with the WHERE clause to remove only those
records that matches specific criteria or condition.
• Syntax:
DELETE FROM table_name WHERE column_name=some_value
• Example: remove the records of those persons from the resident table whose
first_name is equal to Almaz.
• Note:
– The WHERE clause in the DELETE statement specifies which record or records
should be deleted. If you omit the WHERE clause, all records will be deleted.
Remove Existing Data . . . Cont.
• The delete php code must be redirect to the List of
all files after successful deletion using:
–header ( ) function
• header (“location: select_resident.php”);
Refer Lab Materials !
Backup MySQL database using phpMyAdmin
• It is always a good practice to take a regular backup your database.
• There are three ways you can use to take backup of your MySQL database.
– Using SQL Command through PHP.
– Using MySQL binary mysqldump through PHP.
– Using phpMyAdmin user interface.
• phpMyAdmin user interface is very easy for you to take backup of your database.
– To back up your MySQL database using phpMyAdmin click on the "export" link on
phpMyAdmin main page.
– Choose the database you wish to backup,
– check the appropriate SQL options and
– enter the name for the backup file.
Attend Lab class to do the above task!
More examples on database connectivity:
Opening connection or connecting to database
Creating and Selecting database
Sending data
Retrieving data
Searching data
Updating data
Removing data