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

Advanced IP-Chapter-4 - Lect-8, 9

The document discusses how to manipulate MySQL databases using PHP. It covers connecting to a MySQL database, creating and dropping databases, and provides code examples of these operations. Key PHP functions covered include mysql_connect(), mysql_query(), and mysql_close().

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Advanced IP-Chapter-4 - Lect-8, 9

The document discusses how to manipulate MySQL databases using PHP. It covers connecting to a MySQL database, creating and dropping databases, and provides code examples of these operations. Key PHP functions covered include mysql_connect(), mysql_query(), and mysql_close().

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

1

Chapter 4 :
Manipulating MySQL
Databases with PHP
What is Database?
2

 A database is a separate application that stores a


collection of data.
 Each database has one or more distinct APIs for
creating, accessing, managing, searching, and
replicating the data it holds.
 Other kinds of data stores can be used, such as files
on the file system or large hash tables in memory but
data fetching and writing would not be so fast and
easy with those type of systems.
Database cont…
3
 So now a days we use Relational Database Management
Systems (RDBMS) to store and manage huge volume of data.
 This is called relational database because all the data is stored
into different tables and relations are established using primary
keys or other keys known as foreign keys.
 A RDBMS is a software that:
 Enables you to implement a database with tables, columns,

and indexes.
 Guarantees the Referential Integrity between rows of various

tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from

various tables.
RDBMS Terminology:
4
 Before we proceed to explain MySQL database system,
lets revise few definitions related to database.
 Database: A database is a collection of tables, with
related data.
 Table: A table is a matrix with data. A table in a database
looks like a simple spreadsheet.
 Column: One column (data element) contains data of
one and the same kind, for example the column postcode.
 Row: A row (= tuple, entry or record) is a group of
related data, for example the data of one subscription.
 Redundancy: Storing data twice, redundantly to make
the system faster.
cont...
5
 Primary Key: A primary key is unique. A key value can not
occur twice in one table. With a key you can find at most one
row.
 Foreign Key: A foreign key is the linking pin between two
tables.
 Compound Key: A compound key (composite key) is a key
that consists of multiple columns, because one column is not
sufficiently unique.
 Index: An index in a database resembles an index at the back
of a book.
 Referential Integrity: Referential Integrity makes sure that a
foreign key value always points to an existing row.
MySQL Database:
6

 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 released under an open-source license. So
you have nothing to pay to use it.
 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.
cont...
7
 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).
Cont...
8

 MySQL is customizable. The open source GPL (General


Public License ) license allows programmers to modify the
MySQL software to fit their own specific environments.
 MySQL works very well in combination of various
programming languages like PERL, C, C++, JAVA and PHP.
 Out of these languages, PHP is the most popular one because
of its web application development capabilities.
 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.
cont...
9

 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");
cont...
10

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>
The Important MySQL Functionality Along With
PHP: MySQL Connection Using PHP Script:
11

 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

mysql_connect(server, user, passwd);


Cont...
12
 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.
Closing a connection
13

 You can disconnect from MySQL database anytime


using another PHP function mysql_close().
 This function takes a single parameter which is a

connection returned by mysql_connect() function.


Syntax:
bool mysql_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.


Example to connect to a MySQL server:
14
<html><head><title>Connecting MySQL Server</title></head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body></html>
Create Database using PHP Script:
15

 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.
Example to create a database:
16

<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 />';
cont...
17

$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);
?>
</body></html>
Drop Database using PHP Script:
18

 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.
Example to delete a database:
19

<html><head><title>Deleting 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 />';
Cont...
20

$sql = 'DROP DATABASE TUTORIALS';


$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete database: ' . mysql_error());
}
echo "Database TUTORIALS deleted successfully\n";
mysql_close($conn);
?>
</body></html>
WARNING:
21

 While deleting a database using PHP script, it does


not prompt you for any confirmation.
 So be careful while deleting a MySQL database.
 Once you get connection with MySQL server, it is
required to select a particular database to work with.
 This is because there may be more than one database
available with MySQL Server.
Selecting MySQL Database Using PHP
Script:
22

 PHP provides function mysql_select_db to select a


database.
 It returns TRUE on success or FALSE on failure.

Syntax:
bool mysql_select_db( db_name, connection );
 db_name
 Required - MySQL Database name to be selected
 connection
 Optional - if not specified then last opened connection
by mysql_connect will be used.
Here is the example showing you how to select a database.

23

<html><head><title>Selecting MySQL
Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
cont...
24

if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'TUTORIALS' );
mysql_close($conn);
?>
</body> </html>
NOTE:
25

 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.
Numeric Data Types:
26

 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. The following list shows the common numeric data
types and their descriptions.
 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.
Numeric Data Types cont…
27

 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.
cont...
28

 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. You can specify a width of up
to 11 digits.
Numeric Data Types cont…
29
 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.
The MySQL date and time data types are:
30

 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.
date and time data types cont…
31

 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.
String Types:
32

 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.
cont...
33

 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 or TEXT.
 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.
cont...
34

 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.
The table creation command requires:
35

 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);
cont...
36

 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.
Creating Tables Using PHP Script:
37

 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:
Here is an example to create a table using PHP script:
<html><head>
<title>Creating MySQL Tables</title>
</head><body>
cont...
38

<?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 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 )); ";
cont…
39

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>
cont...
40

 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 ;


Dropping Tables Using PHP Script:
41

 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';
cont...
42

$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 );
cont…
43

if(! $retval )
{
die('Could not delete table: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
</body></html>
Lab Example To Connect And Create A Database.
NB: since you don't know the username, servername
and password, make these parameters empty.
44
<?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);
?>

You might also like