PHP Unit V
PHP 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.
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.
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
*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:
<?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();
?>
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.
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.
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.
“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.
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$my_file = 'file.txt';
$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';
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';
fwrite($handle, $data);
fwrite($handle, $new_data);
$my_file = 'file.txt';
fclose($handle);
$my_file = 'file.txt';
unlink($my_file);