Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Unit V

SYLLABUS: Files and directories: create and delete files, opening file for writing, reading
or appending. Writing or appending to file. Working with directories, Building a text editor, File
Uploading & Downloading.
MySQL and PHP: interacting with MySQL using PHP, Performing basic database
operations, (DML) (Insert, Delete, Update, Select), Setting query parameter, Working with Data.

MySQL
What is a Database?
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 also 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.
Nowadays, we use relational database management systems 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.

Data Base Terminology:


Database : A database is a collection of tables, with related data.
Table : A table is a matrix(rows and coloumn) with data. A table in a database looks
like a simple spreadsheet.
Column : One column contains data of one and the same kind.
for example: the column empname.
Row : A row is a group of related data.
for example: the data of one employ details.
Redundancy : Storing data twice, redundantly to make the system faster.
Primary Key : A primary key is unique. A key value cannot occur twice in one table. With
a key, you can only find one row.
Foreign Key : A foreign key is the linking pin between two tables.

MySQL Database:
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL
is developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
 MySQL is released under an open-source license. So you have nothing to pay to use it.
 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 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).
 MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.

Administrative MySQL Command


The list of commands which you will use to work with MySQL database:
CREATE Databasename: This will be used to create a database in the MySQL workarea.
USE Databasename : This will be used to select a database in the MySQL workarea.
SHOW DATABASES : Lists out the databases that are accessible by the MySQL DBMS.
SHOW TABLES : Shows the tables in the database once a database has been selected with
the use command.
SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key information,
whether NULL is permitted, defaults, and other information for a table.

MySQL - PHP
Interacting with MySQL using PHP:
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 the MySQL database and to manipulate the data
records inside the MySQL database. You would require to call the PHP functions in the same way
you call any other PHP function.

MySQL DataTypes:
A data type defines what kind of value a column can hold: integer data, character data, date and
time data, binary strings, and so on. Each column in a database table is required to have a name and a
data type. An MySQL developer must decide what type of data that will be stored inside each column
when creating a table.
Note: Data types might have different names in different database. And even if the name is the same,
the size and other details may be different.
In MySQL there are three main data types: text, number, and date.
1. Text data types:
Data type Description
CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255
characters
VARCHAR(size) Same as CHAR data type but difference is it Holds a variable length string.
Note: If you put a greater value than 255 it will be converted to a TEXT
type
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of
data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an
ENUM list. If a value is inserted that is not in the list, a blank value will be
inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
SET Similar to ENUM except that SET may contain up to 64 list items and can
store more than one choice

Number data types:


Data type Description
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of
digits may be specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*. The maximum number of digits may
be specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The
maximum number of digits may be specified in the size parameter. The
maximum number of digits to the right of the decimal point is specified in the
d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an
negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero
instead of a negative number.

Date data types:


Data type Description
DATE() A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the
Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09
03:14:07' UTC
TIME() A time. Format: HH:MI:SS
Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR() A year in two-digit or four-digit format.
Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-
digit format: 70 to 69, representing years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time.
TIMESTAMP also accepts various formats, like YYYYMMDDHHMISS, YYMMDDHHMISS,
YYYYMMDD, or YYMMDD.
Constraints on Columns:
After the data type, you can specify other optional attributes for each column:
 NOT NULL : Each row must contain a value for that column, null values are not allowed
 DEFAULT value: Set a default value that is added when no other value is passed
 UNSIGNED : Used for number types, limits the stored data to positive numbers and zero
 AUTO INCREMENT : MySQL automatically increases the value of the field by 1 each
time a new record is added
 PRIMARY KEY : Used to uniquely identify the rows in a table. The column with primary
key setting is often an ID number, and is often used with AUTO_INCREMENT.
PHP Connect to MySQL:
PHP work with a MySQL database using either:
 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)
PDO will work on 12 different database systems, whereas MySQLi will only work with
MySQL databases.
when using MySQLi extension there are two ways to conncect with MySQL database.
1. MySQLi (object-oriented)
2. MySQLi (procedural)
Before we can access data in the MySQL database, we need to be able to connect to the server:

1. Open a Connection to MySQL using MySQLi Object-Oriented:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname="databasename";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
2. Open a Connection to MySQL using MySQLi Procedural:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PHP Create a MySQL Database Using MySQLi object oriented.
A database consists of one or more tables.nThe CREATE DATABASE statement is used to
create a database in MySQL.
Ex: create a database named "myDB":
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
$res= conn->query($sql);
if ($res)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
PHP Create a MySQL Table Using MySQLi object oriented:

A database table has its own unique name and consists of columns and rows. The CREATE
TABLE statement is used to create a table in MySQL.

Ex: create a table named "Students", with five columns: "id", "firstname", "lastname",
"email" and "contactno":

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE students (id INT(6),firstname VARCHAR(30),
lastname VARCHAR(30),email VARCHAR(50),contactno int(10))";
$res=$conn->query($sql);
if ($res)
{
echo "Table Student is created successfully";
}
else
{
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Insert Data Into MySQL Using MySQLi object oriented:
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted
Syntax:
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...);
insert.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email,contactno)VALUES
('giri', 'babu', 'giri.cslecturer@gmail.com',1234567890)";
$res=$conn->query($sql);
if ($res)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Select Data From a MySQL Database Using MySQLi object oriented:


The SELECT statement is used to select data from one or more tables. There are two ways to
select data from a table.
1. Selecting Selected columns from a table.
Syntax: SELECT column_name(s) FROM table_name.
Ex: Select firstname,lastname from students.
2. we can use the * character to select ALL columns from a table:
Syntax: SELECT * FROM table_name.
Ex: Select * from students;
Select.php:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "id: " . $row["firstname"]. " - Name: " . $row["lastname"]." ". $row["email"]."<br>";
}
}
else
{
echo "0 results";
}
$conn->close();
?>

In the above program, First, we set up an SQL query that selects the firstname,lastname and
email columns from "students" table. The next line of code runs the query and puts the resulting data
into a variable called "$result".
Then, the function num_rows() checks if there are more than zero rows returned. If there are
more than zero rows returned, the function fetch_assoc() puts all the results into an associative array
that we can loop through. The while() loop loops through the result set and outputs the data from the
firstname, last name and email columns.

Delete Data From a MySQL Table Using MySQLi object oriented:


The DELETE statement is used to delete records from a table:
Syntax: DELETE FROM table_name WHERE some_column = some_value;
Ex: Delete from students where contactno=12345;

Note: The WHERE clause specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!

Delete.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM students WHERE contactno=12345";
$res=$conn->query($sql);
if ($res)
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Update Data In a MySQL Table Using MySQLi object oriented:
The UPDATE statement is used to update existing records in a table:
Syntax: UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value
Ex: UPDATE students SET firstname="ravi" WHERE firstname=12345;
WHERE clause specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!
Update.php:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE students SET firstname="ravi" WHERE firstname=12345";
$res=$conn->query($sql);
if($res)
{
echo "Record updated successfully";
}
else
{
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Limit Data Selections From a MySQL Database:
Select statement of MySQL is used to return all the records. Returning a large number of
records can impact on performance. MySQL provides a LIMIT clause that is used to specify the
number of records to return.
Assume a table contains 100 members students records but we wish to select all records from 1
- 30 (inclusive) from a table. The SQL query would then look like this:
$sql = "SELECT * FROM Orders LIMIT 30";
If we want to select records 16 - 25 (inclusive) Mysql also provides a way to handle this: by
using OFFSET.
The SQL query return only 10 records, start on record 16 (OFFSET 15)":
$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";
Also the above command written in below format also valid
$sql = "SELECT * FROM Orders LIMIT 15, 10";
Note: The numbers are reversed when you use a comma.

Query string in PHP:


Imagine you have a URL:
http://www.mywebsite.com/page.php?id=5&name=php
Then the query string is:
?id=5&name=php
In this case, the query consists of two parts: a key id with value 5, and a key name with
value php.
You can access the value of the query string keys using this code:
$id = $_GET['id'];
The above code gets the value of id, which is 5 in this case.
File Handling
What is a file?
A file is a collection of data that is stored on disk and that can be manipulated as a single unit
by its name.
What is a directory?
A directory is a file that acts as a folder for other files. A directory can also contain other
directories (subdirectories); a directory that contains another directory is called the parent directory of
the directory it contains.
A directory tree includes a directory and all of its files, including the contents of all
subdirectories. (Each directory is a "branch" in the "tree.") A slash character alone (`/') is the name of
the root directory at the base of the directory tree hierarchy; it is the trunk from which all other files or
directories branch.

Handling files: File handling is the concept of reading the file contents as well as writing the
contents. PHP providing no of functions to read and write the file contents. If we want to read and
write contents of file, first we need to open the file with the specified file mode.
Mode specifies the access type of the file or stream. It can have the following possible values:

“r”(Read) : It represents Read only. It reads the file contents. It starts at the
beginning of the file.

“r+”(Read/Write) : It represents Read/Write. It starts at the beginning of the file.

“w”(Write) : It represents Write only. It opens and clears the contents of file or
create a new file if it doesn‟t exist.

“w+”(Write/Read) : It is same as Write mode, we can also read the file contents. It
opens and clears the contents of file or creates a new file if it
doesn‟t exist.

“a”(append) : It represents Write only. It opens and writes the new text at end
of the file or creates a new file if it doesn‟t exist.

“a+”(append/Read) : It is same as append mode, we can also represents Read/Write. It


preserves the file‟s content by writing to the end of the file.

File handling Functions:

1. fopen( ) (Function open file or URL):


The fopen() function in PHP is an inbuilt function which is used to open a file or an URL. It
contains two arguments filename and filemode. The filename and mode to be checked are sent as
parameters to the fopen() function and it returns a file pointer resource if a match is found and a False
on failure. The error output can be hidden by adding an „@‟ in front of the function name.
Syntax: fopen ( $file, $mode)
Here $file: It is a mandatory parameter which specifies the file.
$mode: It is a mandatory parameter specifies the access type of the file or stream

Open file for write mode:

Ex: $my_file = 'file.txt';

$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file

Read a File: fread() is a function used to read data from a file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'r');

$data = fread($handle,filesize($my_file));

Write to a File: fwrite() is a method used to write new data into a file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);

$data = 'This is the data';

fwrite($handle, $data);

Append to a File: append is a method used to add new data at end of an existing file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);

$data = 'New data line 1';

fwrite($handle, $data);

$new_data = "\n".'New data line 2';

fwrite($handle, $new_data);

Close a File: fclose() is a function used to close a file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);


//write some data here

fclose($handle);

Delete a File: unlink() is a function used to delete an existing file.

$my_file = 'file.txt';

unlink($my_file);

You might also like