CH8 - Database Programming
CH8 - Database Programming
8.
DATABASE
PROGRAMMING
WITH
PHP
www.sarojpandey.com.np
-‐
1
PHP
has
support
for
over
20
databases,
including
the
most
popular
commercial
and
open
source
varieties.
Relational
database
systems
such
as
MySQL,
PostgreSQL,
and
Oracle
are
the
backbone
of
most
modern
dynamic
web
sites.
In
these
are
stored
shopping-‐cart
information,
purchase
histories,
product
reviews,
user
information,
credit-‐card
numbers,
and
sometimes-‐even
web
pages
themselves.
8.1
SQL
SQL
stands
for
Structured
Query
Language,
and
it
is
a
very
powerful
and
diverse
language
used
to
create
and
query
databases.
The
loose
structure
and
flexibility
of
this
language
make
it
an
ideal
candidate
for
the
web.
There
are
many
database
applications
available
for
developers
to
use
for
free,
such
as
MySQL.
Some
of
the
basic
functions
of
SQL
are
inputting,
modifying,
and
dropping
data
from
databases.
Coupled
with
the
use
of
web
languages
such
as
HTML
and
PHP,
SQL
becomes
an
even
greater
tool
for
building
dynamic
web
applications.
With
a
SQL
backend,
it
is
fairly
simple
to
store
user
data,
email
lists,
or
other
kinds
of
dynamic
data.
E-‐Commerce
web
sites,
community
sites,
and
online
web
services
rely
on
SQL
databases
to
manage
user
data
or
process
user
purchases.
SQL
has
become
popular
among
web
developers
due
to
its
flexibility
and
simplicity.
With
some
basic
knowledge
of
HTML,
PHP,
and
a
database
program
such
as
MySQL,
a
developer
becomes
capable
of
creating
complex
websites
and
applications
while
relying
on
online
web
services
to
provide
a
SQL
backend
in
which
user
data
is
stored.
What
Can
SQL
do?
www.sarojpandey.com.np
-‐
2
DML
and
DDL
SQL
can
be
divided
into
two
parts:
The
Data
Manipulation
Language
(DML)
and
the
Data
Definition
Language
(DDL).
The query and update commands form the DML part of SQL:
The
DDL
part
of
SQL
permits
database
tables
to
be
created
or
deleted.
It
also
defines
indexes
(keys),
specifies
links
between
tables,
and
imposes
constraints
between
tables.
The
most
important
DDL
statements
in
SQL
are:
What's
a
Database?
A
SQL
database
is
nothing
more
than
an
empty
shell,
like
a
vacant
warehouse.
It
offers
no
real
functionality
whatsoever,
but
does
provide
a
virtual
space
to
store
data.
Data
is
stored
inside
of
database
objects
called
tables,
and
tables
are
the
containers
that
actually
hold
specific
types
of
data,
such
as
numbers,
files,
strings,
and
dates.
A
single
database
can
house
hundreds
of
tables
containing
1,000s
of
table
columns
each.
SQL
coins
the
term
query
as
the
name
for
its
commands.
Basically,
all
SQL
code
is
written
in
the
form
of
a
query
statement
and
then
executed
against
a
database.
All
SQL
queries
perform
some
type
of
data
operation
such
as
selecting
data,
inserting/updating
data,
or
creating
data
objects
such
as
SQL
databases
and
SQL
tables.
Each
query
statement
begins
with
a
clause
such
as
SELECT,
UPDATE,
CREATE
or
DELETE.
www.sarojpandey.com.np
-‐
3
CREATE
SQL
CREATE
is
the
command
used
to
create
data
objects,
including
everything
from
new
databases
and
tables
to
views
and
stored
procedures.
SQL
Create
Database
Query:
CREATE
DATABASE
MyDatabase;
Data
is
stored
inside
SQL
tables,
which
are
contained
within
SQL
databases.
A
single
database
can
house
hundreds
of
tables,
each
playing
its
own
unique
role
in
the
database
schema.
SQL
tables
are
comprised
of
table
rows
and
columns.
Table
columns
are
responsible
for
storing
many
different
types
of
data,
like
numbers,
texts,
dates,
and
even
files.
There
are
many
different
types
of
table
columns
and
these
data
types
vary,
depending
on
how
the
SQL
table
has
been
created
by
the
SQL
developer.
A
table
row
is
a
horizontal
record
of
values
that
fit
into
each
different
table
column.
SQL
Create
Table
Query:
USE
mydatabase;
CREATE
TABLE
orders
(
id
INT
IDENTITY(1,1)
PRIMARY
KEY,
customer
VARCHAR(50),
day_of_order
DATETIME,
product
VARCHAR(50),
quantity
INT);
The
first
line
of
the
example,
"USE
mydatabase;",
is
pretty
straightforward.
This
line
defines
the
query
scope
and
directs
SQL
to
run
the
command
against
the
MyDatabase
object
we
created
earlier.
The
line
starting
with
the
CREATE
clause
is
where
we
are
actually
going
to
tell
SQL
to
create
the
new
table,
which
is
named
orders.
Each
table
column
has
its
own
set
of
guidelines
or
schema,
and
the
lines
of
code
above
contained
in
parenthesis
()
are
telling
SQL
how
to
go
about
setting
up
each
column
schema.
Table
columns
are
presented
in
list
format,
and
each
schema
is
separated
with
a
comma
(,).
INSERT
INSERT
command
will
insert
a
new
data
row
into
SQL
table,
orders.
www.sarojpandey.com.np
-‐
4
INSERT
INTO
orders
(customer,day_of_order,product,
quantity)
VALUES('KCC','8/1/08','Pen',4);
SELECT
SELECT
queries
are
the
most
commonly
used
SQL
commands,
SELECT
query
will
return
records
from
the
orders
table
that
was
created
previously.
SQL
Select
Query
Template:
SELECT
table_column1,
table_column2,
table_column3
FROM
my_table;
e.g.
SELECT
*
FROM
orders;
{*
refers
to
all.}
Select
queries
require
two
essential
parts.
The
first
part
is
the
"WHAT",
which
determines
what
we
want
SQL
to
go
and
fetch.
The
second
part
of
any
SELECT
command
is
the
"FROM
WHERE".
It
identifies
where
to
fetch
the
data
from,
which
may
be
from
a
SQL
table,
a
SQL
view,
or
some
other
SQL
data
object.
e.g.
SELECT
customer,
day_of_order,
product,
quantity
FROM
orders;
WHERE
CONDITION
The
WHERE
clause
sets
a
conditional
statement,
and
it
can
be
used
with
any
type
of
SQL
query.
As
the
select
query
executes,
SQL
processes
one
row
at
a
time.
Each
time
the
conditional
statement
is
met
(returns
true),
a
row
is
returned
as
a
result.
SQL
WHERE
is
essentially,
a
filtering
mechanism
for
SQL
queries
and
is
a
tremendous
asset
to
any
aspiring
SQL
developer.
e.g.
SELECT
*
FROM
orders
WHERE
customer
=
‘KCC’
UPDATE
SQL
UPDATE
is
the
command
used
to
update
existing
table
rows
with
new
data
values.
UPDATE
is
a
very
powerful
command
in
the
SQL
world.
It
has
the
ability
to
update
every
single
row
in
a
database
with
the
execution
of
only
a
single
query.
Due
to
UPDATE's
supreme
authority,
it
is
best
to
always
include
a
WHERE
clause
when
working
with
UPDATE
query
statements.
That
way,
there
won’t
be
any
chances
that
accidentally
update
more
rows.
Syntax:
UPDATE
table_name
SET
values
…
WHERE
condition;
UPDATE
orders
SET
quantity
=
'18',
Product
=
External
Disk'
WHERE
id
=
'1'
www.sarojpandey.com.np
-‐
5
DELETE
In
the
SQL
world,
databases,
rows,
and
columns
all
have
one
thing
in
common:
once
a
DELETE
statement
has
been
executed
successfully
against
them,
the
data
they
once
contained
is
lost
forever!
DELETE
-‐
Deletes
any
number
of
rows
from
a
data
object.
DELETE
queries
work
much
like
UPDATE
queries
and
like
UPDATE,
it
is
much
advised
to
always
use
a
WHERE
condition
when
running
any
delete
query
or
else
you
risk
deleting
too
much
data.
DELETE
FROM
orders
WHERE
customer
=
'KCC’;
DROP
-‐
Removes
table
columns,
tables,
and
all
data
objects
SQL
applications.
SQL
DROP
is
another
command
that
removes
data
from
the
data
store.
The
DROP
command
must
be
performed
on
SQL
objects
including
databases,
tables,
table
columns,
and
SQL
views.
Dropping
any
of
these
objects
removes
them
completely
from
your
SQL
application
and
all
data
contained
in
any
of
the
data
objects
dropped
are
lost
forever.
DROP
TABLE
orders;
DROP
DATABASE
mydatabase;
DROP
COLUMN
column_name
TRUNCATE
-‐
SQL
TRUNCATE
is
the
fastest
way
to
remove
all
data
from
a
SQL
table,
leaving
nothing
but
an
empty
shell.
You
might
choose
to
use
this
command
when
all
the
data
inside
of
a
table
needs
to
be
removed
but
you'd
like
the
table
column
definitions
to
remain
intact.
TRUNCATE
TABLE
orders;
[Refer
to
the
subject
‘Database
Management
System’
for
details
on
SQL.]
8.2
CRUD
In
computer
programming,
create,
read,
update
and
delete
(CRUD)
are
the
four
basic
functions
of
persistent
storage.
Sometimes
CRUD
is
expanded
with
the
words
retrieve
instead
of
read,
modify
instead
of
update
or
destroy
instead
of
delete.
It
is
also
sometimes
used
to
describe
user
interface
conventions
that
facilitate
viewing,
searching,
and
changing
information;
often
using
computer-‐based
forms
and
reports.
Another variation of CRUD is BREAD, an acronym for "Browse, Read, Edit, Add, Delete".
The
acronym
CRUD
refers
to
all
of
the
major
functions
that
are
implemented
in
relational
database
applications.
Each
letter
in
the
acronym
can
map
to
a
standard
SQL
statement.
www.sarojpandey.com.np
-‐
6
Operation
SQL
8.3
Database
Connectivity
MySQL
is
the
most
popular
open-‐source
database
system.
MySQL
is
a
database.
The
data
in
MySQL
is
stored
in
database
objects
called
tables.
A
table
is
a
collection
of
related
data
entries
and
it
consists
of
columns
and
rows.
Databases
are
useful
when
storing
information
categorically.
A
company
may
have
a
database
with
the
following
tables:
"Employees",
"Products",
"Customers"
and
"Orders".
Before
you
can
access
data
in
a
database,
you
must
create
a
connection
to
the
database.
In
PHP,
this
is
done
with
the
mysql_connect()
function.
Syntax
mysql_connect(servername,username,password);
Example
In
the
following
example
we
store
the
connection
in
a
variable
($con)
for
later
use
in
the
script.
The
"die"
part
will
be
executed
if
the
connection
fails:
<?php
$con
=
mysql_connect("localhost","peter","abc123");
if
(!$con)
{
die('Could
not
connect:
'
.
mysql_error());
}
//
some
code
?>
www.sarojpandey.com.np
-‐
7
Closing
a
Connection
The
connection
will
be
closed
automatically
when
the
script
ends.
To
close
the
connection
before,
use
the
mysql_close()
function:
<?php
$con
=
mysql_connect("localhost","root","root");
if
(!$con)
{
die('Could
not
connect:
'
.
mysql_error());
}
//
some
code
mysql_close($con);
?>
Insert
Data
Into
a
Table
<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>
When
a
user
clicks
the
submit
button
in
the
HTML
form
in
the
example
above,
the
form
data
is
sent
to
"insert.php".
The
"insert.php"
file
connects
to
a
database,
and
retrieves
the
values
from
the
form
with
the
PHP
$_POST
variables.
Then,
the
mysql_query()
function
executes
the
INSERT
INTO
statement,
and
a
new
record
will
be
added
to
the
"Persons"
table.
www.sarojpandey.com.np
-‐
8
Here
is
the
"insert.php"
page:
<?php
$con
=
mysql_connect("localhost","root","root");
if
(!$con)
{
die('Could
not
connect:
'
.
mysql_error());
}
mysql_select_db("my_db",
$con);
$sql="INSERT
INTO
Persons
(FirstName,
LastName,
Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if
(!mysql_query($sql,$con))
{
die('Error:
'
.
mysql_error());
}
echo
"1
record
added";
mysql_close($con);
?>
The following example selects the same data as the example above, but will display the data in an HTML table:
<?php
$con
=
mysql_connect("localhost","root","root");
if
(!$con)
{
die('Could
not
connect:
'
.
mysql_error());
}
mysql_select_db("my_db",
$con);
$result
=
mysql_query("SELECT
*
FROM
Persons");
echo
"<table
border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row
=
mysql_fetch_array($result))
www.sarojpandey.com.np
-‐
9
{
echo
"<tr>";
echo
"<td>"
.
$row['FirstName']
.
"</td>";
echo
"<td>"
.
$row['LastName']
.
"</td>";
echo
"</tr>";
}
echo
"</table>";
mysql_close($con);
?>
The following example updates some data in the "Persons" table:
<?php
$con
=
mysql_connect("localhost","root","root");
if
(!$con)
{
die('Could
not
connect:
'
.
mysql_error());
}
mysql_select_db("my_db",
$con);
mysql_query("UPDATE
Persons
SET
Age=36
WHERE
FirstName='Ram'
AND
LastName='Karki'");
mysql_close($con);
?>
Delete
Data
Syntax
DELETE
FROM
table_name
WHERE
some_column
=
some_value
The following example deletes all the records in the "Persons" table where LastName='Karki':
<?php
$con
=
mysql_connect("localhost","root","root");
www.sarojpandey.com.np
-‐
10
if
(!$con)
{
die('Could
not
connect:
'
.
mysql_error());
}
mysql_select_db("my_db",
$con);
mysql_query("DELETE
FROM
Persons
WHERE
LastName='Karki'");
mysql_close($con);
?>
http://php.net/manual/en/ref.mysql.php
http://www.w3schools.com/php/php_ref_mysql.asp
ODBC
is
an
Application
Programming
Interface
(API)
that
allows
you
to
connect
to
a
data
source
(e.g.
an
MS
Access
database).
With
an
ODBC
connection,
you
can
connect
to
any
database,
on
any
computer
in
your
network,
as
long
as
an
ODBC
connection
is
available.
Here is how to create an ODBC connection to a MS Access Database:
Note
that
this
configuration
has
to
be
done
on
the
computer
where
your
web
site
is
located.
If
you
are
running
Internet
Information
Server
(IIS)
on
your
own
computer,
the
instructions
above
will
work,
but
if
your
web
site
is
located
on
a
remote
server,
you
have
to
have
physical
access
to
that
server,
or
ask
your
web
host
to
set
up
a
DSN
for
you
to
use.
The
odbc_connect()
function
is
used
to
connect
to
an
ODBC
data
source.
The
function
takes
four
parameters:
the
data
source
name,
username,
password,
and
an
optional
cursor
type.
The odbc_exec() function is used to execute an SQL statement.
The
following
example
creates
a
connection
to
a
DSN
called
northwind,
with
no
username
and
no
password.
It
then
creates
an
SQL
and
executes
it:
$conn=odbc_connect('northwind','','');
$sql="SELECT
*
FROM
customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
The
odbc_fetch_row()
function
is
used
to
return
records
from
the
result-‐set.
This
function
returns
true
if
it
is
able
to
return
rows,
otherwise
false.
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)
The
odbc_result()
function
is
used
to
read
fields
from
a
record.
This
function
takes
two
parameters:
the
ODBC
result
identifier
and
a
field
number
or
name.
The code line below returns the value of the first field from the record:
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");
The odbc_close() function is used to close an ODBC connection.
odbc_close($conn);
An
ODBC
Example
www.sarojpandey.com.np
-‐
13
The
following
example
shows
how
to
first
create
a
database
connection,
then
a
result-‐set,
and
then
display
the
data
in
an
HTML
table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if
(!$conn)
{exit("Connection
Failed:
"
.
$conn);}
$sql="SELECT
*
FROM
customers";
$rs=odbc_exec($conn,$sql);
if
(!$rs)
{exit("Error
in
SQL");}
echo
"<table><tr>";
echo
"<th>Companyname</th>";
echo
"<th>Contactname</th></tr>";
while
(odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo
"<tr><td>$compname</td>";
echo
"<td>$conname</td></tr>";
}
odbc_close($conn);
echo
"</table>";
?>
</body>
</html>
In
PHP,
we
can
insert
the
content
of
one
PHP
file
into
another
PHP
file
before
the
server
executes
it.
The
include
and
require
statements
are
used
to
insert
useful
codes
written
in
other
files,
in
the
flow
of
execution.
• require
will
produce
a
fatal
error
(E_COMPILE_ERROR)
and
stop
the
script
• include
will
only
produce
a
warning
(E_WARNING)
and
the
script
will
continue
So,
if
you
want
the
execution
to
go
on
and
show
users
the
output,
even
if
the
include
file
is
missing,
use
include.
Otherwise,
in
case
of
FrameWork,
CMS
or
a
complex
PHP
application
coding,
always
use
require
to
include
a
key
file
to
the
flow
of
execution.
This
will
help
avoid
compromising
your
application's
security
and
integrity,
just
in-‐case
one
key
file
is
accidentally
missing.
Including
files
saves
a
lot
of
work.
This
means
that
you
can
create
a
standard
header,
footer,
or
menu
file
for
all
your
web
pages.
Then,
when
the
header
needs
to
be
updated,
you
can
only
update
the
header
include
file.
Syntax
include
'filename';
or
require
'filename';
Basic Example
Assume
that
you
have
a
standard
header
file,
called
"header.php".
To
include
the
header
file
in
a
page,
use
include/require:
<html>
<body>
<?php
include
'header.php';
?>
<h1>Welcome
to
my
home
page!</h1>
<p>Some
text.</p>
</body>
</html>
Example 2
Assume we have a standard menu file that should be used on all pages.
"menu.php"
File
Content
echo
'<a
href="/default.php">Home</a>
<a
href="/tutorials.php">Tutorials</a>
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div
class="leftmenu">
<?php
include
'menu.php';
?>
</div>
<h1>Welcome
to
my
home
page.</h1>
<p>Some
text.</p>
</body>
</html>
Example 3
Assume we have an include file with some variables defined ("vars.php"):
<?php
$color='red';
$car='BMW';
?>
Then the variables can be used in the calling file:
<html>
<body>
<h1>Welcome
to
my
home
page.</h1>
<?php
include
'vars.php';
echo
"I
have
a
$color
$car";
//
I
have
a
red
BMW
?>
</body>
</html>
~