0% found this document useful (0 votes)
10 views

Integrate database with a website

Nothig is found below the sun

Uploaded by

Estifanos Girma
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)
10 views

Integrate database with a website

Nothig is found below the sun

Uploaded by

Estifanos Girma
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/ 98

MANKUL COLLEGE

DEPARTMENT OF WEB DEVELOPMENT AND


DATABASE ADMINISTRATION
COURSE TITLE: Integrating Database with a Website
COURSE CODE: EIS WDDBA3 M08 0322

PREPARED BY: Tekalegn B.


DEC. 2016 E.C
11/14/2023 Tekalegn B.
PHP- Hyper Text preprocessor
Web Site developing languages Their long form
HTML Hyper text markup language (.html)
CSS Cascading style sheet (.css)
PHP Hyper text preprocessor(.php)
MySQL Structured Query Language(.sql)

Database

HTML
CSS PHP SQL
JS

11/14/2023 Tekalegn B.
Database
Database is collection of interrelated data. Data is known facts
that can be recorded and that have implicit meaning. E.g. names,
telephone numbers, courses you take, address of peoples you
know.

Database Management System(DBMS) is a collection of


programs that enables users to create and maintain a
database. The DBMS is a general-purpose software system
that facilitates the processes of defining, constructing,
manipulating, and sharing databases among various users
and applications

11/14/2023 Tekalegn B.
Database is just a computerized record keeping system or a
kind of electronic filing cabinet. Database is a repository for
collection of computerized data files.
 Database is a shared collection of logically related data
designed to meet the information needs of an
organization. Since it is a shared corporate resource, the
database is integrated with minimum amount of or no
duplication.

 Database is a collection of logically related data where


these logically related data comprises entities, attributes,
relationships, and business rules of an organization's
information.
11/14/2023 Tekalegn B.
Types of Database
There are different types of database. These are:-
 SQL  used for both web and android
development and it is local server
SQLite  used in mobile app without internet
connection and store data on local memory on
phone.
MySQL  XAMPP and WAMPP
Firebase  using internet connection for
application , no need of server give cloud server,
security and storage is high.
11/14/2023 Tekalegn B.
SQL(structured query Language)
 SQL is a standard Computer language for accessing and
manipulating a database. To access and manipulate data in
database using SQL in MySQL, Access,
sybase,DB2,oracle, SQL Server and others.
 SQL used to access and manipulate databases and it is
ANSII standards.
What can SQL do?
1. CRUDE(Create, retrieve, update, delete) data from / in database
2. Execute quires against a database
3. Insert records in a database
4. Create /delete new table/database
5. Set permissions on tables, procedures, and views.
11/14/2023 Tekalegn B.
SQL has different versions but all support at least the major
commands such as select, update, delete, insert, and where .
 SQL allows you to access a database
 SQL is an ANSI standard computer language
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert new records from a database
 SQL can delete records from a database
 SQL can update records in a database
 SQL is easy to learn
To build a website that shows data from a databases; we will need
 RDBMS(Ms .Access, SQL server, MySQL)
 Server side scripting languages(PHP, ASP)
 Use HTML or CSS or java Script
 Use SQL to get the data you want
11/14/2023 Tekalegn B.
Database Languages
There are four types of database languages:-
Data Definition Language (DDL)
Data Manipulation Language (DML)
Data Control Language (DCL)
Transaction Control Language (TCL)

11/14/2023 Tekalegn B.
Data Definition Language (DDL)
Allows user to describe and name entitles, attributes and
relationships required for the application.
– Used to define the database schema
The language is used to create database, tables, alter them,
etc.
With this, you can also rename the database, or drop them.
It specifies the database schema. The DDL statements
include
• CREATE: Create new database, table, etc.
• ALTER: Alter(changes) existing database, table, etc.
• DROP: Drop or delete the database
• RENAME: Set a new name for the table.

11/14/2023 Tekalegn B.
Data Manipulation Language (DML)
– Language for accessing and manipulating the data
organized by the appropriate data model, Some times
called query language.
• The language used to manipulate the database like
inserting data, updating table, retrieving record from a
table, etc. is known as Data Manipulation Language −
• SELECT: Retrieve or extract data from the database
• INSERT: Insert a new data in to a database table
• UPDATE: Update data in a database table
• DELETE: Delete deletes a database table
Procedural DML:
– user specifies what data is required & how to get the data.
Non-Procedural DML:
– user specifies what data is required but not how it is to be
retrieved.
11/14/2023 Tekalegn B.
Data Control Language(DDL)
Grant privilege to a user using the GRANT statement. In
the same way, revoke the privilege using the REVOKE
statement. Both of these statements come under the Data
Control Language (DCL). −
• GRANT: Give privilege to access the database.
• REVOKE: Take back the privilege to access the database.

11/14/2023 Tekalegn B.
Transaction Control Language
Manage transactions in the Database using the Transaction
Control Language:-
• COMMIT: Save the work.
• SAVEPOINT: Set a point in transaction to rollback later
• ROLLBACK: Restores since last commit

11/14/2023 Tekalegn B.
Server Side Scripting Language

11/14/2023 Tekalegn B.
Web –servers

Server is a computer that contain documents, videos, audios, and other


relevant information and accessed by different users from different
place.
Web-servers is a server that used for web application and web site file
and document warehouse.
There are different web servers that used for localhost website and
project applications. These are:-
 XAMPP Apache MySQL PHP Perl for Linux and Mac
 WAMPP Apache MySQL PHP Perl for window operating system

11/14/2023 Tekalegn B.
Web page is a document typically written in HTML that
is almost always accessible via HTTP or pages on which
information is displayed on the web. It can be Static or
dynamic web page.
Static web page means that what is displayed does not
change until the underlying HTML or XML is changed.

Dynamic web page means when the content that is


displayed changes in response to actions taken by the
user. This kinds of web page is developed using scripting
language.

11/14/2023 Tekalegn B.
Scripting Language is a programming language in a
simple text format. Generally, code written in a scripting
language does not have to compiled- unlike, for example,
code written in C++ or Visual basic. Instead , it is
interpreted at the time of execution. Web browsers can
interpret certain scripting language.

Scripts can be written to run either server-side or client-


side.
A script must be interpreted at the time it is requested
from the web server. Each scripting language has its own
script interpreter called a script engine.

11/14/2023 Tekalegn B.
There are different languages in computer world. These may:
 Client Side script Language(html, css and JavaScript)
 Server side script Language(html (php, ASP.NET, java,
ColdFusion, Perl, Ruby, Go, Python, and server-side JavaScript.)
Client-side Script is executed on the client, by the browser.
Server side Scripting Language is executed on the server.
ASP---Active Server Pages
JSP---java via java Server pages
Php---hyper text Preprocessors

11/14/2023 Tekalegn B.
Server-side Scripting
Server side scripting is a web server technology in which a user’s
request is fulfilled by running a script directly on the web server to
generate dynamic web pages.
It is usually used to provide interactive web sites that interface to
database or other data stores.
The primary advantage of server-side scripting is the ability to high
customize the response based on the user’s requirements, access
rights, or queries into data stores.
Server-side web scripting is mostly about connecting websites to
back end servers, such as databases. This enables two-way
communication:
i. Client to Server: customer-enter information as request
ii. Server to Client: Web pages can be assembled from back end-
server to give output.

11/14/2023 Tekalegn B.
What is PHP?
PHP stands for hyper text preprocessor and is a server-
side language. This means that the script is run on your
web server , not on the user’s browser, so you do not need
to worry about compatibility issues.
PHP support many databases (MySQL, Informix, oracle,
Sybase, solid, PostgreSQL, Generic ODBC, Microsoft
SQL Server etc.).
PHP files can contain text, HTML tags and scripts. Like
others files written in server side language. PHP files are
returned to the browsers as plain HTML and it has a file
extension of “.php”, “.php3”, or “.phtml”.

11/14/2023 Tekalegn B.
Why PHP?
 Allows easy storage and retrieval of information from
supported database
 Accessibility: You can reach the internet from any
browsers, any device, any time, anywhere.
 Manageability: It does not require distribution of
application code and it is easy to change code.
 Security: The source code is not exposed. Once user is
authenticated , can only allow certain actions. It also
allows encryption.
 Scalability: Web-based 3-tier architecture can scale out.

11/14/2023 Tekalegn B.
What you need to get started?
Hopefully you have established a basic idea of what server-side
scripting is , and when you should use it. Next you need some basic
requisites to be able to write and execute scripts. Basically you need:
1. First for all you need a computer with a web server installed. PHP
uses web servers such as Apache, IIS etc. But for this course we will
install WAMPP or XAMPP servers. WAMPP server refers to a
software stack for the Microsoft windows operating system, created
by Romain Bourdon and consisting of the apache web server,
OpenSSL for SSL(Secure Socket Layer) Support , MySQL database
and PHP programming language.
WAMPP server has a root directory called WWW. So all the files of a
website must be stored under this directory (C:\wampp\www) to be
executed by the server.
2. You need some sort of text editor such as Notepade, Notepade++,
etc. to write the script.
11/14/2023 Tekalegn B.
3. You also need a web browser to display the web content.
The web browser can be internet explorer, Mozilla firefox ,
Opera, and Google Chrome etc.
Generally, to connect the database with a website first we must
follow the following steps.
1. First download and install XAMPP or WAMPP server software's
2. Create a database inside XAMPP or WAMPP
3. Download and install text editors(sublime text, notepad++..)
4. Write a PHP file and save as .php and connect with database

11/14/2023 Tekalegn B.
PHP(Hyper text Preprocessor)

It is a server side scripting language, and powerful tool for making


dynamic and an interactive web pages.
Each php files can be executed on server. We can see the output on
browsers, but browsers are a client side , the main thing is every
execution held inside a server.
 The structure of PHP is similar to C/C++.
 It supports procedural and object oriented paradigm.
 All php statements end with semicolon(;).
 Each php script must be enclosed in the reserved php tags like
<? Php ?>
 It can be executed on servers (XAMPP and WAMPP).
 Php codes run on server, but browsers are client side
11/14/2023 Tekalegn B.
To write a php program that display any out put is follow steps.
 Install php servers
 Use text editors
 Save a file extensions as .php
Example: a php program print Hello world
<?php
echo “Hello World”;
?>
Php file may contain html, css, java script and php code.
<?php
// this is php single line comment.
/* this is php multiple line comment.*/
?>

11/14/2023 Tekalegn B.
PHP file or code differentiate from other elements in the page by php parsing engine.
The mechanism for doing so is known as ‘escaping to php’. There are four ways to do
this:
I. Canonical PHP tags: the most universally effective PHP tag style
<?php
Your php code here
?>
II. Short-open(SGML-style) tags: short or short-open tags looks like
<?
Your php code here
?>
III. ASP-style tags: mimic the tags used by Active Server page to delineate code blocks.
<%
Your php code here
%>
IV. HTML Script tags: HTML script tags look like this
<script language=“PHP”>
Your php code here
</script>
11/14/2023 Tekalegn B.
PHP Output Statements
PHP has different syntaxes but for maximum compatibility , it is recommended
to use the canonical style or <?php ?> this.
Each code line in PHP must end with a semicolon(;). The semicolon is a
separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: that are echo and print .
ECHO PRINT
 Echo has no return value  Print has return value
 Echo takes Multiple parameters.  Print takes only one argument.
 Echo is marginally faster than print  Print is marginally slower than echo
Syntax: Syntax:
echo outputstament; or print outputstament; or
echo (outputstament); print(outputstament);
Example: Example:
echo “Hello World!!”; print “Hello World!!”;
echo (“Hello World!!”); print (“Hello World!!”);

Return value means whether the print statement is succeeded or not. If the print
statement succeeded, the statement returns 1 otherwise 0.
Error: echo Hello World; because string should be enclosed in quotes.
11/14/2023 Tekalegn B.
Connecting to Databases
• One of the reasons for PHP’s popularity as a web scripting language is its
support for a wide range of relational database system. This support makes it
easy for web developers to create data-driven web-sites and to prototype new
web applications quickly and efficiently.
• PHP supports more than fifteen different database engines, including Microsoft
SQL server, IBM DB2, PostgreSQL, MySQL, and Oracle. Using database in
application s helps us to: Read/Write data, Store More data, have better
organized data, faster access to data, easier to manipulate and relate data to other
data.
• Database is a collection (set ) of tables. We should have 1database for 1
application.
• Tables: is a set of rows and columns. It represents a single concept such as
product, customers, order etc. we can create relationship among tables.
• Columns: a set of data of single data type. Example FirstName, LastName,
Email, Password etc. . Columns have types such as strings, integers, float, date
etc.

11/14/2023 Tekalegn B.
• Rows: is a single record of data. Example “Abebe”, “Kebede”,
[email protected].
• Fields: is the intersection of rows and column. E.g. FirstName: “Abebe”
• Index: Data structure on a table to increase look up speed.
• Foreign Key: table columns whose values references rows in another
table. It is the foundation of relational table.
• Primary Key: is a unique key of the table. It is not occur twice in one
table
PHP allows developers to interact with databases in two ways:
1. By using a customized database specific extension
2. By using the database neural PHP Data Objects(PDO)extension
While the PDO extension is more portable, many developers still find it
preferable to use the native database extensions, especially when the native
extension offers better performance or more features than the PDO version.
Of the various database engines supported by PHP, the most popular one by
far is MySQL. Both PHP and MySQL are open-source.
11/14/2023 Tekalegn B.
Connect to MySQL server/Existing Database
PHP provides us different APIs(Application Program Interfaces) to deal
with MySQL server databases. These are:
 mysql ( original MySQL)
 mysqli (MySQL improved)
 PDO (PHP data object)
The difference between these APIs are shown on the table given below.
Features mysql mysqli PDO
Introduced V2.0 V5.0 V5.1
Deprecated V5.5 - -
Included with PHP yes yes Yes
Pre-configured for MySQL yes yes
Other database supported Yes
Procedural Interface yes yes
Object-oriented interface Yes Yes
Prepare statements yes Yes
11/14/2023 Tekalegn B.
PHP database interactions in five steps:
 Create a database connection
 Perform Database query
 Use returned data if any
 Release returned data
 Close database connection
Creating a database connection
Before we enable do anything with MySQL in PHP , we should first connect
to the MySQL server using specific connection variables. Connection
variables consist of the following common parameters, of which the first
one is required while others are optional;-
 Host name: this is the name of the server. We can change to whatever
host is acting as MySQL server.
 User name: the root user of the system
 User name’s password: this is encrypted written with the form for
security.
11/14/2023 Tekalegn B.
The common function in PHP that uses for server connection is mysql_connect() or
mysqli_connect() function.
The General syntax of database connection in mysqli is as follow:
connection.php
connection.php
<?php
<?php
$server=“localhost”;
$server="localhost";
$dbuser=“root”;
$dbuser="root";
$dbpassword=“”;
$dbpassword="";
$dbname=“test”;
$dbname="student";
$conn=mysqli_connect($server, $dbuser,
$conn=mysqli_connect($server, $dbuser,
$dbpassword, $dbname);
$dbpassword, $dbname);
if (!$conn)
if (!$conn)
{
{
die("connection failed:".mysqli_connect_error);
die("connection
}
failed:".mysqli_connect_error);
}
$sql="CREATE DATABASE loginpage";
if(mysqli_query($conn, $sql))
echo "The database connected successfuly!!";
echo "The databses creaed successfuly!!";
mysqli_close($conn)
else
?>
echo "error creating a
database".$mysqli_error;
//This connection used when we already
Mysqli_close($conn)
created adatabse
?>
11/14/2023 Tekalegn B.
PHP & MySQL
• PHP will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL database which is released
under an open-source license. So you have nothing to pay to use it.
• MySQL is a fast, easy-to-use RDBMS used being used for many small and big
businesses.
• MySQL is developed, marketed, and supported by MySQL AB, which is a
Swedish company.
• MySQL is a very powerful program in its own right. It handles a large subset of
the functionality of the most expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL is becoming so popular because of many good reasons.
– MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
– MySQL works very quickly and works well even with large data sets.
– MySQL is very friendly to PHP, the most appreciated language for web development.
– MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
11/14/2023 Tekalegn B.
PHP & MySQL Cont...
• MySQL is customizable. The open source GPL (General Public License )
license allows programmers to modify the MySQL software to fit their
own specific environments.
• PHP provides various functions to access MySQL database and to
manipulate data records inside MySQL database.
• You would require to call PHP functions in the same way you call any
other PHP function.
• The PHP functions for use with MySQL have the following general
format:
mysql_function(value,value,...);
• The second part of the function name is specific to the function, usually a
word that describes what the function does. The following are two of the
functions which we will use in our lesson.
mysqli_connect($connect);
mysqli_query($connect,"SQL statement");
11/14/2023 Tekalegn B.
PHP & MySQL cont...
Following example shows a generic syntax of PHP to call any MySQL
function.
<html><head><title>PHP with MySQL</title></head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval )
{
die ( "Error: a related error message" );
}
// Otherwise MySQL or PHP Statements
?>
</body></html>
11/14/2023 Tekalegn B.
Important Functions in PHP
There are different functions in PHP that have different purposes.
These are:
mysqli_connect($server, $user, $password, $databasename);
mysqli_select_db($connection, “database name”): Equivalent to
the MySQL command USE; makes the selected database the
active one.
mysqli_query($connection, "query”): used to send any type of
MySQL command to the server.
mysqli_fetch_rows(“results variable from query): used to return
a rows of the entire results of a database query.
mysqli_fetch_array(“results variable from query): used to
return several rows of the entire results of a database query.
mysqli_free_result(“result variable from query”): used to
release the returned results.
mysqli_error(): shows the error message that has been returned
directly from the MySQL Tekalegn
11/14/2023 server.
B.
The Important MySQL Functionality Along With
PHP: MySQL Connection Using PHP Script:
• PHP provides mysql_connect() function to open a database
connection.
• This function takes five parameters and returns a MySQL link
identifier on success, or FALSE on failure.
Syntax:
– connection
mysqli_connect(server, user, passwd);
• server
– Optional - The host name running database server. If not specified then default
value is localhost:3036.
• user
– Optional - The username accessing the database. If not specified then default
is the name of the user that owns the server process.
• passwd
– Optional - The password of the user accessing the database. If not specified
then default is an empty password.
– Note: There are more available parameters, but the ones listed above are the most
important.
11/14/2023 Tekalegn B.
Closing a connection
• You can disconnect from MySQL database anytime using another PHP function
mysqli_close().
• This function takes a single parameter which is a connection returned by
mysqli_connect() function.
Syntax:
bool mysqli_close ( resource $link_identifier );
– If a resource is not specified then last opened database is closed.
– This function returns true if it closes connection successfully otherwise it returns
false.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
Create Database using PHP Script:

• PHP uses mysql_query function to create or delete a


MySQL database. This function takes two parameters
and returns TRUE on success or FALSE on failure.
• Syntax:
bool mysql_query( sql, connection );
• Sql
Required - SQL query to create or delete a MySQL
database
• connection
Optional - if not specified then last opened connection by
mysql_connect will be used.

11/14/2023 Tekalegn B.
Example to create a database:
<html><head><title>Creating MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE TUTORIALS';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
echo "Database TUTORIALS created successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
</body></html>
Drop Database using PHP Script:

• PHP uses mysql_query function to create or delete a


MySQL database.
• This function takes two parameters and returns TRUE
on success or FALSE on failure.
Syntax:
bool mysqli_query(connection, sql);
• sql
Required - SQL query to create or delete a MySQL database
• connection
Optional - if not specified then last opened connection by
mysqli_connect will be used.

11/14/2023 Tekalegn B.
Example to delete a database:
<html><head><title>Deleting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
Warning
if(! $conn ) •While deleting a database using
{ PHP script, it does not prompt
die('Could not connect: ' . mysql_error()); you for any confirmation.
} •So be careful while deleting a
echo 'Connected successfully<br />'; MySQL database.
$sql = 'DROP DATABASE TUTORIALS'; •Once you get connection with
$retval = mysql_query( $sql, $conn ); MySQL server, it is required to
if(! $retval )
select a particular database to
{
die('Could not delete database: ' . mysql_error());
work with.
} • This is because there may be
echo "Database TUTORIALS deleted successfully\n"; more than one database available
mysql_close($conn); with MySQL Server.
?>
</body></html>
11/14/2023 Tekalegn B.
Selecting MySQL Database Using PHP Script:

• PHP provides function mysqli_select_db to select


a database.
• It returns TRUE on success or FALSE on failure.
Syntax:
bool mysqli_select_db(connection ,db_name);
• db_name
– Required - MySQL Database name to be selected
• connection
– Optional - if not specified then last opened connection
by mysql_connect will be used.
11/14/2023 Tekalegn B.
Here is the example showing you how to select a database.
<html><head><title>Selecting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysqli_select_db( $conn,'TUTORIALS' );
mysql_close($conn);
?>
</body> </html>
11/14/2023 Tekalegn B.
NOTE:
• Properly defining the fields in a table is important to the overall
optimization of your database.
• You should use only the type and size of field you really need to use;
• don't define a field as 10 characters wide if you know you're only going
to use 2 characters.
• These types of fields (or columns) are also referred to as data types, after
the type of data you will be storing in those fields.
• MySQL uses many different data types, broken into three categories:
– numeric, date and time, and string types.
• MySQL uses all the standard ANSI SQL numeric data types, so if you're
coming to MySQL from a different database system, these definitions
will look familiar to you.

11/14/2023 Tekalegn B.
Numeric Data Types
• INT - A normal-sized integer that can be signed or unsigned. If signed, the
allowable range is from -2147483648 to 2147483647. If unsigned, the
allowable range is from 0 to 4294967295. You can specify a width of up to
11 digits.
• TINYINT - A very small integer that can be signed or unsigned. If signed,
the allowable range is from -128 to 127. If unsigned, the allowable range is
from 0 to 255. You can specify a width of up to 4 digits.
• SMALLINT - A small integer that can be signed or unsigned. If signed, the
allowable range is from -32768 to 32767. If unsigned, the allowable range
is from 0 to 65535. You can specify a width of up to 5 digits.
• MEDIUMINT - A medium-sized integer that can be signed or unsigned. If
signed, the allowable range is from -8388608 to 8388607. If unsigned, the
allowable range is from 0 to 16777215. You can specify a width of up to 9
digits.
• BIGINT - A large integer that can be signed or unsigned. If signed, the
allowable range is from -9223372036854775808 to
9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615.
11/14/2023 You canTekalegn
specify
B. a width of up to 11 digits.
Numeric Data Types cont…
• FLOAT(M,D) - A floating-point number that cannot be unsigned.
You can define the display length (M) and the number of decimals
(D). This is not required and will default to 10,2, where 2 is the
number of decimals and 10 is the total number of digits (including
decimals). Decimal precision can go to 24 places for a FLOAT.
• DOUBLE(M,D) - A double precision floating-point number that
cannot be unsigned. You can define the display length (M) and the
number of decimals (D). This is not required and will default to 16,4,
where 4 is the number of decimals. Decimal precision can go to 53
places for a DOUBLE. REAL is a synonym for DOUBLE.
• DECIMAL(M,D) - An unpacked floating-point number that cannot
be unsigned. In unpacked decimals, each decimal corresponds to one
byte. Defining the display length (M) and the number of decimals (D)
is required. NUMERIC is a synonym for DECIMAL.
11/14/2023 Tekalegn B.
The MySQL date and time data types are:

• DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-


31. For example, December 30th, 1973 would be stored as 1973-12-30.
• DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS
format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example,
3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30
15:30:00.
• TIMESTAMP - A timestamp between midnight, January 1, 1970 and
sometime in 2037. This looks like the previous DATETIME format, only
without the hyphens between numbers; 3:30 in the afternoon on December
30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
• TIME - Stores the time in HH:MM:SS format.
• YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified
as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the
length is specified as 4, YEAR can be 1901 to 2155. The default length is 4.
11/14/2023 Tekalegn B.
String Types:
• Although numeric and date types are fun, most data you'll store will be in
string format. This list describes the common string datatypes in MySQL.
• CHAR(M) - A fixed-length string between 1 and 255 characters in length
(for example CHAR(5)), right-padded with spaces to the specified length
when stored. Defining a length is not required, but the default is 1.
• VARCHAR(M) - A variable-length string between 1 and 255 characters in
length; for example VARCHAR(25). You must define a length when
creating a VARCHAR field.
• BLOB or TEXT - A field with a maximum length of 65535 characters.
BLOBs are "Binary Large Objects" and are used to store large amounts of
binary data, such as images or other types of files. Fields defined as TEXT
also hold large amounts of data; the difference between the two is that
sorts and comparisons on stored data are case sensitive on BLOBs and are
not case sensitive in TEXT fields. You do not specify a length with BLOB
11/14/2023 Tekalegn B.
or TEXT.
cont...
• TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum
length of 255 characters. You do not specify a length with TINYBLOB or
TINYTEXT.
• MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a
maximum length of 16777215 characters. You do not specify a length with
MEDIUMBLOB or MEDIUMTEXT.
• LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum
length of 4294967295 characters. You do not specify a length with
LONGBLOB or LONGTEXT.
• ENUM - An enumeration, which is a fancy term for list. When defining an
ENUM, you are creating a list of items from which the value must be selected
(or it can be NULL). For example, if you wanted your field to contain "A" or
"B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only
those values (or NULL) could ever populate that field.

11/14/2023 Tekalegn B.
The table creation command requires:
• Name of the table
• Names of fields
• Definitions for each field
Syntax:
• Here is generic SQL syntax to create a MySQL table:
– CREATE TABLE table_name (column_name column_type);
• tutorials_tbl( tutorial_id INT NOT NULL AUTO_INCREMENT, tutorial_title
VARCHAR(100) NOT NULL, tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE, PRIMARY KEY ( tutorial_id ));
Here few items need explanation:
• Field Attribute NOT NULL is being used because we do not want this field to
be NULL. SO if user will try to create a record with NULL value then MySQL
will raise an error.
• Field Attribute AUTO_INCREMENT tells to MySQL to go ahead and add the
next available number to the id field.
• Keyword PRIMARY KEY is used to define a column as primary key. You can
use multiple columns separated by comma to define a primary key.
11/14/2023 Tekalegn B.
Creating Tables Using PHP Script:
• To create new table in any existing database you would need to use PHP function
mysql_query().
• You will pass its second argument with proper SQL command to create a table.
Example:
<html><head> <title>Creating MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';

11/14/2023 Tekalegn B.
cont…

$sql = "CREATE TABLE tutorials_tbl( ". "tutorial_id INT NOT NULL


AUTO_INCREMENT, ". "tutorial_title VARCHAR(100) NOT NULL, ".
"tutorial_author VARCHAR(40) NOT NULL, ". "submission_date DATE,
". "PRIMARY KEY ( tutorial_id )); ";
mysql_select_db( 'TUTORIALS' );
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
</body></html>
11/14/2023 Tekalegn B.
Dropping Tables Using PHP Script:
• It is very easy to drop an existing MySQL table.
• But you need to be very careful while deleting any existing table because data lost
will not be recovered after deleting a table.
Syntax:
• Here is generic SQL syntax to drop a MySQL table:
• DROP TABLE table_name ;
• To drop an existing table in any database you would need to use PHP function
mysql_query().
• You will pass its second argument with proper SQL command to drop a table.
Example:
<html>
<head><title>Creating MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
11/14/2023 Tekalegn B.
cont...
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
If(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "DROP TABLE tutorials_tbl";
mysql_select_db( 'TUTORIALS' );
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete table: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
</body></html>
11/14/2023 Tekalegn B.
Lab Example To Connect And Create A Database.
NB: since you don't know the username, servername
and password, make these parameters empty.
<?php
$conn = mysql_connect("","" ,"" );
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
echo "Database test_db created successfully\n";
mysql_close($conn);
11/14/2023 Tekalegn B.
?>
Inserting data into MySQL table

• To insert data into MySQL table you would need to use


SQL INSERT INTO command.
Syntax:
• Here is generic SQL syntax of INSERT INTO command to
insert data into MySQL table:
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES ( value1, value2,...valueN );
• To insert string data types it is required to keep all the
values into double or single quote, for example:- "value".
• You can use same SQL INSERT INTO command into PHP
function mysql_query() to insert data into a MySQL table.
Example:
• This example will take three parameters from user and will
insert them into MySQL table:
11/14/2023 Tekalegn B.
Example
<html><head><title>Add New Record in MySQL
Database</title></head><body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error()); }
$tutorial_title = $_POST['tutorial_title'];
$tutorial_author = $_POST['tutorial_author'];
$submission_date = $_POST['submission_date'];
11/14/2023 Tekalegn B.
$sql = "INSERT INTO tutorials_tbl ".
"(tutorial_title,tutorial_author, submission_date) ".
"VALUES ".
"('$tutorial_title','$tutorial_author','$submission_date')";
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{?>
11/14/2023 Tekalegn B.
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="600" border="0" cellspacing="1"
cellpadding="2">
<tr><td width="250">Tutorial Title</td><td>
<input name="tutorial_title" type="text"
id="tutorial_title"></td>
</tr><tr><td width="250">Tutorial Author</td><td>
<input name="tutorial_author" type="text"
id="tutorial_author"></td>
</tr><tr><td width="250">Submission Date [ yyyy-mm-dd
] </td><td>
11/14/2023 Tekalegn B.
<input name="submission_date" type="text"
id="submission_date"></td></tr>
<tr><td width="250"> </td><td> </td></tr><tr><td
width="250"> </td><td>
<input name="add" type="submit" id="add" value="Add
Tutorial"></td>
</tr></table></form>
<?Php
}
?>
</body></html>

11/14/2023 Tekalegn B.
Insert.html
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>

11/14/2023 Tekalegn B.
Insert.php
<?php
$con=mysqli_connect(““, ““ , ““ , "my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .
mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
11/14/2023
mysqli_close($con); Tekalegn B.
?>
Fetching Data
• The SQL SELECT command is used to fetch data from MySQL database.
• Here is generic SQL syntax of SELECT command to fetch data from
MySQL table:
SELECT field1, field2,...fieldN table_name1, table_name2...[WHERE
Clause][OFFSET M ][LIMIT N]
• You can use one or more tables separated by comma to include various
condition using a WHERE clause. But WHERE clause is an optional part
of SELECT command.
• You can fetch one or more fields in a single SELECT command.
• You can specify star (*) in place of fields. In this case SELECT will return
all the fields.
• You can specify any condition using WHERE clause.
• You can specify an offset using OFFSET from where SELECT will start
returning records. By default offset is zero
• You can limit the number of returned
11/14/2023
using LIMIT attribute.
Tekalegn B.
Fetching Data Using PHP Script:

• You can use same SQL SELECT command into


PHP function mysql_query().
• This function is used to execute SQL command
and later another PHP function
mysql_fetch_array() can be used to fetch all the
selected data.
• This function returns row as an associative array,
a numeric array, or both.
• This function returns FALSE if there are no more
rows.
• Below is a simple example to fetch records from
tutorials_tbl table.
11/14/2023 Tekalegn B.
Example:
Try out following example to display all the records from
tutorials_tbl table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author,
submission_date FROM tutorials_tbl';

11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title:
{$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-----------------------
---------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
• The content of the rows are assigned to the variable $row
and the values in row are then printed.
• NOTE: Always remember to put curly brackets when you
want to insert an array value directly into a string.
• In above example the constant MYSQL_ASSOC is used as
the second argument to PHP function mysql_fetch_array(),
so that it returns the row as an associative array.
• With an associative array you can access the field by using
their name instead of using the index.
• PHP provides another function called mysql_fetch_assoc()
which also returns the row as an associative array.

11/14/2023 Tekalegn B.
Example:
• Try out the following example to display all the
records from tutorial_tbl table using
mysql_fetch_assoc() function.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser,
$dbpass);
If(! $conn )
{ die('Could not connect: ' . mysql_error());}

11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author,
submission_date FROM tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_assoc($retval))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-------------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
• You can also use the constant MYSQL_NUM, as the second
argument to PHP function mysql_fetch_array().
• This will cause the function to return an array with numeric
index.
Example:
• Try out following example to display all the records from
tutorials_tbl table using MYSQL_NUM argument.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error()); }
11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval,
MYSQL_NUM))
{ echo "Tutorial ID :{$row[0]} <br> ". "Title:
{$row[1]} <br> ". "Author: {$row[2]} <br> ".
"Submission Date : {$row[3]} <br> ". "-------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
All the above three examples
11/14/2023 Tekalegn B. will produce same result.
Releasing Memory:
• Its a good practice to release cursor memory at the end of
each SELECT statement.
• This can be done by using PHP function
mysql_free_result().
• Below is the example to show how it has to be used.
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}

11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{ echo "Tutorial ID :{$row[0]} <br> ". "Title:
{$row[1]} <br> ". "Author: {$row[2]} <br> ".
"Submission Date : {$row[3]} <br> ". "-------
<br>";}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
Using WHERE clause

• While fetching data you can write as complex


SQL as you like. Procedure will remain same as
mentioned above.
• We have seen SQL SELECT command to fetch
data from MySQL table.
• We can use a conditional clause called WHERE
clause to filter out results.
• Using WHERE clause we can specify a selection
criteria to select required records from a table.
11/14/2023 Tekalegn B.
Syntax:
• Here is generic SQL syntax of SELECT command with
WHERE clause to fetch data from MySQL table:
SELECT field1, field2,...fieldN table_name1,
table_name2...[WHERE condition1 [AND [OR]]
condition2.....
• You can use one or more tables separated by comma to
include various condition using a WHERE clause. But
WHERE clause is an optional part of SELECT
command.
• You can specify any condition using WHERE clause.
• You can specify more than one conditions using AND or
OR operators.
11/14/2023 Tekalegn B.
• A WHERE clause can be used along with
DELETE or UPDATE SQL command also to
specify a condition.
• The WHERE clause works like a if condition in
any programming language. This clause is used to
compare given value with the field value
available in MySQL table. If given value from
outside is equal to the available field value in
MySQL table then it returns that row.
• Here is the list of operators which can be used
with WHERE clause.
• Assume field A holds 10 and field B holds 20 then
11/14/2023 Tekalegn B.
Operator Description Example

Checks if the value of two operands is equal or


= (A = B) is not true.
not, if yes then condition becomes true.

Checks if the value of two operands is equal or


!= not, if values are not equal then condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater
> than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then condition (A < B) is true.
becomes true.
Checks if the value of left operand is greater
>= than or equal to the value of right operand, if (A >= B) is not true.
yes then condition becomes true.
Checks if the value of left operand is less than
<= or equal to the value of right operand, if yes (A <= B) is true.
then condition becomes true.
11/14/2023 Tekalegn B.
Fetching Data Using PHP Script:

• You can use same SQL SELECT command with


WHERE CLAUSE into PHP function
mysql_query().
• This function is used to execute SQL command
and later another PHP function
mysql_fetch_array() can be used to fetch all the
selected data.
• This function returns row as an associative array,
a numeric array, or both. This function returns
FALSE if there are no more rows.
11/14/2023 Tekalegn B.
Example:

Following example will return all the records from tutorials_tbl table
for which author name is Sanjay:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM tutorials_tbl
WHERE tutorial_author="Sanjay"';

11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "--------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
11/14/2023 ?> Tekalegn B.
Updating data
• There may be a requirement where existing data in a
MySQL table need to be modified.
• You can do so by using SQL UPDATE command.
• This will modify any field value of any MySQL table.
Syntax:
• Here is generic SQL syntax of UPDATE command to
modify data into MySQL table:
UPDATE table_name SET field1=new-value1, field2=new-
value2[WHERE Clause]
• You can update one or more field all together.
• You can specify any condition using WHERE clause.
• You can update values in a single table at a time.
• The WHERE clause is very useful when you want to
update selected rows in a table.
11/14/2023 Tekalegn B.
Updating Data Using PHP Script:
• You can use SQL UPDATE command with or
without WHERE CLAUSE into PHP function
mysql_query().
• Try out following example to update
tutorial_title field for a record having tutorial_id
as 3.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
11/14/2023
{ die('Could not connect:
Tekalegn B.
' . mysql_error());}
$sql = 'UPDATE tutorials_tbl SET
tutorial_title="Learning JAVA" WHERE
tutorial_id=3';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not update data: ' . mysql_error());}
echo "Updated data successfully\n";
mysql_close($conn);
?>

11/14/2023 Tekalegn B.
Deleting data

• If you want to delete a record from any MySQL table then


you can use SQL command DELETE FROM.
Syntax:
• Here is generic SQL syntax of DELETE command to delete
data from a MySQL table:
DELETE FROM table_name [WHERE Clause]
• If WHERE clause is not specified then all the records will
be deleted from the given MySQL table.
• You can specify any condition using WHERE clause.
• You can delete records in a single table at a time.
• The WHERE clause is very useful when you want to delete
selected rows in a table.

11/14/2023 Tekalegn B.
Deleting Data Using PHP Script:

• You can use SQL DELETE command with or without


WHERE CLAUSE into PHP function mysql_query().
• Try out following example to delete a record into
tutorial_tbl whose tutorial_id is 3.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}

11/14/2023 Tekalegn B.
$sql = 'DELETE FROM tutorials_tbl
WHERE tutorial_id=3';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not delete data: ' . mysql_error());}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
• We have seen SQL SELECT command to fetch data from MySQL
table.
• We can also use a conditional clause called WHERE clause to
select required records.
• A WHERE clause with equal sign (=) works fine where we want to
do an exact match.
• Like if "tutorial_author = 'Sanjay'". But there may be a requirement
where we want to filter out all the results where tutorial_author
name should contain "jay".
• This can be handled using SQL LIKE clause along with WHERE
clause.
• If SQL LIKE clause is used along with % characters then it will
work like a meta character (*) in Unix while listing out all the files
or directories at command prompt.
• Without a % character LIKE clause is very similar to equal sign
along with WHERE clause.

11/14/2023 Tekalegn B.
Using LIKE clause

• Here is generic SQL syntax of SELECT command along with LIKE


clause to fetch data from MySQL table:
• SELECT field1, field2,...fieldN table_name1, table_name2...WHERE
field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'
• You can specify any condition using WHERE clause.
• You can use LIKE clause alongwith WHERE clause.
• You can use LIKE clause in place of equal sign.
• When LIKE is used alongwith % sign then it will work like a meta
character search.
• You can specify more than one conditions using AND or OR
operators
• A WHERE...LIKE clause can be used alongwith DELETE or
UPDATE SQL command also to specify a condition.
11/14/2023 Tekalegn B.
Using LIKE clause inside PHP Script:

• You can use similar syntax of WHERE...LIKE


clause into PHP function mysqli_query().
• This function is used to execute SQL command
and later another PHP function
mysqli_fetch_array() can be used to fetch all the
selected data if WHERE...LIKE clause is used
along with SELECT command.
• But if WHERE...LIKE clause is being used with
DELETE or UPDATE command then no further
PHP function call is required.
11/14/2023 Tekalegn B.
Example:
• Try out following example to return all the records from
tutorials_tbl table for which author name contains jay:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM tutorials_tbl
WHERE tutorial_author LIKE "%jay%"';

11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
11/14/2023 Tekalegn B.
?>
Using ORDER BY clause
• We have seen SQL SELECT command to fetch data from MySQL table.
• When you select rows, the MySQL server is free to return them in any
order, unless you instruct it otherwise by saying how to sort the result.
• But you sort a result set by adding an ORDER BY clause that names the
column or columns you want to sort by.
Syntax:
• Here is generic SQL syntax of SELECT command along with ORDER BY
clause to sort data from MySQL table:
SELECT field1, field2,...fieldN table_name1, table_name2...ORDER BY
field1, [field2...] [ASC [DESC]]
• You can sort returned result on any field provided that filed is being listed
out.
• You can sort result on more than one field.
• You can use keyword ASC or DESC to get result in ascending or
descending order. By default its ascending order.
• You can use WHERE...LIKE clause in usual way to put condition.
11/14/2023 Tekalegn B.
Using ORDER BY clause inside PHP Script:

• You can use similar syntax of ORDER BY clause into PHP function
mysql_query().
• This function is used to execute SQL command and later another PHP
function mysql_fetch_array() can be used to fetch all the selected data.
• Try out following example which returns result in descending order of
tutorial author.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser,
$dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM tutorials_tbl
ORDER BY tutorial_author DESC';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "----------------
<br>";}
echo "Fetched data successfully\n";
11/14/2023
mysql_close($conn); Tekalegn B.
?>
Handling NULL Values
• We have seen SQL SELECT command along with WHERE
clause to fetch data from MySQL table. But when we try to
give a condition which compare field or column value to
NULL it does not work properly.
• To handle such situation MySQL provides three operators
– IS NULL: operator returns true of column value is NULL.
– IS NOT NULL: operator returns true of column value is not
NULL.
– <=> operator compare values, which (unlike the = operator) is true
even for two NULL values
– Conditions involving NULL are special. You cannot use = NULL
or != NULL to look for NULL values in columns. Such
comparisons always fail because it's impossible to tell whether or
not they are true. Even NULL = NULL fails.
• To look for columns that are or are not NULL, use IS NULL
or IS NOT NULL.
11/14/2023 Tekalegn B.
Handling NULL Values in PHP Script:
• You can use if...else condition to prepare a query based on NULL value.
• Following example take tutorial_count from outside and then compare it
with the value available in the table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
if( isset($tutorial_count ))
{ $sql = 'SELECT tutorial_author, tutorial_count
FROM tcount_tbl WHERE tutorial_count =
$tutorial_count';}else{ $sql = 'SELECT
tutorial_author, tutorial_count FROM tcount_tbl
WHERE tutorial_count IS $tutorial_count';}
11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Author:{$row['tutorial_author']} <br> ". "Count:
{$row['tutorial_count']} <br> ". "-----------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

11/14/2023 Tekalegn B.
Database

HTML
CSS PHP SQL
JS

END
THANK
YOU!!!!!!

11/14/2023 Tekalegn B.

You might also like