You are on page 1of 51

WP/WTI Lecture 4:

PHP & MySQL (Part 1 of 2)


Paul Albinson
palbinson@bournemouth.ac.uk
www.bournemouth.ac.uk

Outline

An introduction to MySQL
MySQL APIs
Using our MySQL server
Oracle vs. MySQL
PHP and MySQL

Operational logic
CRUD operations
Data retrieval
Error handling

www.bournemouth.ac.uk

An Introduction to MySQL

www.bournemouth.ac.uk

MySQL

Pronounced
My S Q L

MySQL is the most popular open


source relational database
It primarily competes against
PostgreSQL in the open source RDBMS
market

Owned and maintained by Oracle (but


still free!)

It is fast, reliable, scalable, and easy to


use.
It is very popular and is used in and

www.bournemouth.ac.uk

MySQL Editions
MySQL Community Edition Free!
A excellent RDBMS with all the key
features most users require but it has no
customer support
There is however documentation and a users
forum
It is actually better than the standard
commercial version

Commercial versions Annual


Subscription
Includes customer support

www.bournemouth.ac.uk

Commercial Versions
MySQL Standard Edition ($2,000 a
year)
Basic database features with customer
support
The free community edition is actually
better

MySQL Enterprise Edition ($5,000 a


year)
Improved enterprise management
features
www.bournemouth.ac.uk

Web Architecture
Client

Server
HTTP

Web
front-end
(Apache)

User
Agent

HTTP

www.bournemouth.ac.uk

Middleware
(PHP)

API

Backend
(DB)

MySQL APIs

www.bournemouth.ac.uk

PHP Database Extensions


Database extensions are APIs used
for accessing a database server in
PHP
The link between the middleware and
the backend

There are 2 types of database


extension:
Abstraction layers
Vendor-specific extensions
www.bournemouth.ac.uk

API Types
Abstraction layers:
Unify database interactions so that code
focuses on database functions (query,
insert, delete etc.) rather than individual
DBMSs.
This makes database code more flexible,
just change the configuration to use a
different DBMS and the code still works.

Vendor- specific extensions:


DBMS specific (MySQL in this case)

www.bournemouth.ac.uk

MySQL APIs
PHP has 3 different APIs to use MySQL:
mysql - Standard MySQL Extension
Deprecated,
DO mysql
NOT USE,
it will beuse
removed
Deprecated
- Do Not Use
extension,
mysqli or
PDO instead.
in PHP 7

mysqli - MySQL improved extension


Replaces standard mysql extension (mysql)

PDO - PHP Data Objects

mysql and mysqli procedural functions


look very similar e.g. mysql_query()
mysqli_query() but they are different

www.bournemouth.ac.uk

Mysqli vs. PDO


Green = Advantage over other option

www.bournemouth.ac.uk

Mysqli vs. PDO


For now well start with mysqli
As our work so far has been procedural and as
mysqlis procedural functions are easier for
beginners than PDO well use them for now. PDO will
be considered for WP next semester.

More comparisons:
http://php.net/manual/en/mysqlinfo.api.choosing.php
http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-s
hould-you-use-net-24059

More details on using PDO:


http://www.sitepoint.com/re-introducing-pdo-the-right-w
www.bournemouth.ac.uk
ay-to-access-databases-in-php

Using Our MySQL Server

www.bournemouth.ac.uk

Connection details
To use our MySQL server (available
on Gauda) you need the following
details:
Host: 127.0.0.1
Username: Your regular username e.g.
i767654
Password: See your MYSQL-README file
See the MYSQL-README file in your home
directory (/home/ixxxx - note ixxx represents
your username)
www.bournemouth.ac.uk

Modifying your database


You can modify your database:
Via code Typically SQL within a PHP
script
Via the phpMyAdmin database
management web application
See https://
gauda.bournemouth.ac.uk/gaudadba
Note this currently only works inside BU

Via MySQL workbench (works anywhere)


Guides on using phpMyAdmin and
www.bournemouth.ac.uk
MySQL workbench are provided on MyBU

Oracle Vs. MySQL

www.bournemouth.ac.uk

Oracle vs. MySQL

I like/understand
Oracle, cant I
just use that?

The purpose is not about helping you


choose the right database to use as the
two are built for different markets.
MySQL is excellent for web development
and is a very popular and powerful RDBMS
for this
Oracle is better suited to non-web
applications

We are more interested in the


database structure and mechanisms
rather than their feature sets

www.bournemouth.ac.uk

Data Authentication
It is a process used to verify the
identity of a database user in order to
permit them to access, process or
alter data.
MySQLs implementation:
Grant tables are used to keep track of
users and the privileges that they can
have.
Location can be checked along with the
www.bournemouth.ac.uk

Schema
A database schema contains the definitions of
the tables, views, indexes, users, constraints,
stored procedures, triggers, and other
database-specific objects.
It can be considered as the header file of a
database which describes its structure (blueprint).

A common understanding is that a database


in MySQL is a schema in Oracle.
When using a database, you use schema in Oracle
while you use database in MySQL.
www.bournemouth.ac.uk

Data Types
Both MySQL and Oracle support three
main types: numeric, date and
time, and string.
The main difference is that data types
defined in MySQL are more specific.
For example:
MySQL: INT, DOUBLE, REAL and FLOAT.
Oracle: NUMBER(n,0), FLOAT(24).
www.bournemouth.ac.uk

Data Storage Concepts


In Oracle, tablespaces provide logical
storage space that links a database to the
physical data files.
In MySQL, a storage engine is used to deal
with data storage and retrieval.
For the default storage engine MyISAM, each
database is a directory within the MySQL data
directory where each table of the database is
stored in a separate set of files within the
directory.
www.bournemouth.ac.uk

SQL Queries
Both Oracle and MySQL are RDBMS
which support SQL queries.
However, they have different
implementations of SQL syntax.
Conceptually, they are the same but
practically they are different. Beware of
their differences.
Many DBMSs use their own
implementations of SQL - Notably
Oracle, Microsoft SQL Server and
www.bournemouth.ac.uk

SQL Syntax Examples


Retrieve the first 5 rows from a
database table
MySQL
SELECT columns FROM table ORDER BY key
ASC LIMIT 5;

Oracle
SELECT * FROM (SELECT columns FROM
table ORDER BY key ASC) WHERE ROWNUM
<= 5;
www.bournemouth.ac.uk

PHP and MySQL

www.bournemouth.ac.uk

Database Operation Logic

Connect to
the server

www.bournemouth.ac.uk

Select a
database

Submit a
query

Disconnect
from the
server

Retrieve
data

MySQLi Mapping
DB Operation
Logics

mysqli Extension

Server connection

mysqli_connect()

Database selection

mysqli_select_db()

Query submission

mysqli_query()
mysqli_multi_query()

Data retrieval
(fetch row or rows)

mysqli_fetch_assoc()
mysqli_fetch_array()
mysqli_fetch_all()

And other mysqli_fetch_ variations


Memory free up

mysqli_free_result()

Server disconnection

mysqli_close()

Error handling

mysqli_error()

www.bournemouth.ac.uk

Server Connection
Syntax:

mysqli_connect(host, username,
password,
dbname,
port, socket);
Equivalent MySQL
command:
mysql h host u user p password db
Example:

$conn = mysqli_connect('127.0.0.1',
'i1234567',
For our server 'password','i1234567');
the database name is the same as the
username, in ordinary circumstances it would be
different.

www.bournemouth.ac.uk

Database Selection
Syntax:
mysqli_select_db(connection,dbname
);
Equivalent SQL syntax:
USE dbname;

Example:

$conn = mysqli_connect('127.0.0.1',
'i1234567',
'password');
mysqli_select_db($conn, 'mydb');
Note as you can specify the database when connecting to the
server using mysqli_connect() the only time you would
need to use this is to change databases after connecting.
www.bournemouth.ac.uk

Server Disconnection
Syntax:mysqli_close(dbconnection)
;

Equivalent MySQL command:


exit
Example:
$conn = mysqli_connect('127.0.0.1',
'i1234567',
'password','i1234567');
mysqli_close($conn);
www.bournemouth.ac.uk

CRUD Operations
CRUD stands for Create, Read, Update
and Delete in relational database
applications.
It refers to INSERT/CREATE, SELECT,
UPDATE and DELETE/DROP SQL
statements.
CRUD operations are implemented as SQL
queries/commands.
www.bournemouth.ac.uk

CRUD Operations in PHP


SQL queries are generally created as strings in
PHP
They are executed on the MySQL server by using
mysqli_query() function.
By default, query results are returned as a result
set (mysqli_result object).
They can be then retrieved by using functions
defined in mysqli_result class.
www.bournemouth.ac.uk

CRUD: Create A Table


SQL syntax (basic):
CREATE TABLE table (col
type);
p_id
p_name

Example:INT

VARCHAR (255)

p_stock
INT

$query = "CREATE TABLE IF NOT EXISTS


products (
p_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (p_id),
p_name VARCHAR(255),
p_stock INT
)";
$result = mysqli_query($conn, $query);
www.bournemouth.ac.uk

CRUD: Insert Data


SQL syntax (basic):
INSERT INTO table (col1,
col2)
VALUES (value1, value2);

Example:

$query = "INSERT INTO products (p_id,


p_name, p_stock) VALUES (NULL, 'f',
0);";
$result = mysqli_query($conn,
p_id
p_name
p_stock
$query);
0
www.bournemouth.ac.uk

CRUD: Select Data


SQL syntax (basic):
SELECT * FROM table WHERE col =
'value';

Example:

$query = "SELECT * FROM products


WHERE p_stock = 0;";
$result = mysqli_query($conn,
$query);
p_id

p_name

p_stock

www.bournemouth.ac.uk

CRUD: Update Data


SQL syntax (basic):
UPDATE table SET col =
'value'
WHERE col = 'value';

Example:

$query = "UPDATE products SET p_stock =


21
WHERE p_stock = 0;";
$result = mysqli_query($conn, $query);
p_id

p_name

p_stock

21

www.bournemouth.ac.uk

CRUD: Delete Data


SQL syntax (basic):
DELETE FROM table WHERE col =
'value';

Example:
$query = "DELETE FROM product
WHERE p_stock = 0;";
$result = mysqli_query($conn,
$query);
www.bournemouth.ac.uk

CRUD: Drop/Delete a Table


SQL syntax (basic):
DROP TABLE IF EXISTS
table;

Example:
$query = "DROP TABLE IF EXISTS
products;";
$result = mysqli_query($conn, $query);

www.bournemouth.ac.uk

Data Retrieval Logic in PHP


Query results are normally called data rows
in a database.
These data rows are returned to PHP as a
result set where:
Each data row will be stored in an array.
The key of the array is the table column or
column index.
The value of the array is the data value
corresponding to the column.
Loops/iteration is used to get all data rows.
www.bournemouth.ac.uk

Data Retrieval Diagram


p_id p_nam
e

p_stock

10

11

12

13

Result set

Key

SELECT * FROM products

www.bournemouth.ac.uk

10

11

12

13

Value

10

Array1

Value

11

Array2

Value

12

Array3

Data Retrieval Example


Get a result row as an enumerated array:
Example:

mysqli_fetch_row(
);

$query = "SELECT * FROM products


WHERE p_stock > 0;";
$result = mysqli_query($conn,
$query);
while ($row =
mysqli_fetch_row($result))
{
echo $row[0], $row[1], $row[2];

www.bournemouth.ac.uk

Data Retrieval Example


Fetch a result row as an associative, a
numeric array,
or both:
mysqli_fetch_array(
);
Example with numeric array:
$query = "SELECT p_id, p_stock
FROM products WHERE p_stock >
0;";
$result = mysqli_query($conn, $query);
while ($row =
mysqli_fetch_array($result, MYSQLI_NUM))
{
echo $row[0], $row[1];

www.bournemouth.ac.uk

Data Retrieval Example


Fetch a result row as an associative, a
numeric array,
or both:
mysqli_fetch_array(
);
Example with associative array:
$query = "SELECT p_id, p_stock
FROM products WHERE p_stock >
0;";
$result = mysqli_query($conn, $query);
while ($row =
mysqli_fetch_array($result,
MYSQLI_ASSOC)){
echo $row["p_id"], $row["p_stock"];

www.bournemouth.ac.uk

Data Retrieval Example


Fetch a result row as an associative, a
numeric array,
or both:
mysqli_fetch_array(
);
Example with both numeric and
associative:
$query = "SELECT p_id, p_stock
0;";

FROM products WHERE p_stock >

$result = mysqli_query($conn, $query);


while ($row = mysqli_fetch_array($result,
MYSQLI_BOTH)){
}

echo $row["p_id"], $row[1];

www.bournemouth.ac.uk

Data Retrieval Examples


There are other ways of fetching
results See http://
php.net/manual/en/class.mysqli-resul
t.php

www.bournemouth.ac.uk

Error Handling
Connection error: mysqli_connect()
It will return FALSE if connecting fails
The error can be captured using
mysqli_connect_error()

Query error: mysqli_query()


It will return FALSE if the query fails
The error can be captured with mysqli_error()

PHP function die() is normally used when major


errors are detected
It will terminate the current script and exit the program
www.bournemouth.ac.uk

Error Handling Example


Normal

$conn =
mysqli_connect("127.0.0.1","username",
"password", "db");
if (!$conn) {
die(mysqli_connect_error());
}
echo "<p>Connected!</p>";

Shorthand

$conn =
mysqli_connect("127.0.0.1","username",
"password", "db") or
die(mysqli_connect_error());
www.bournemouth.ac.uk

Error Handling Example


Detailed connection error message

$conn =
mysqli_connect("127.0.0.1","username",
"password", "db");
if (mysqli_connect_error()){
echo "Failed to connect to MySQL: .
mysqli_connect_error();
}
echo "<p>Connected!</p>";

www.bournemouth.ac.uk

Conclusion

www.bournemouth.ac.uk

Further reading

MySQLi in PHP Manual


MySQL 5.x Reference Manual
Ullman Chapters 4,5,8
Welling & Thomson Chapters
8,9,10,11

www.bournemouth.ac.uk

Preview of the next lecture


Cookies
The concept of cookies
CRUD Operations of Cookies
Uses for cookies

www.bournemouth.ac.uk

You might also like