0% found this document useful (0 votes)
192 views57 pages

Open Source Sotware

Uploaded by

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

Open Source Sotware

Uploaded by

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

ADARSH DEGREE

COLLEGE
(Affiliated to Andhra University)
Pendurthi, Visakhapatnam - 531173

Open Source Software


for 3rd BCA Students
1. What is open source software?
Open source software is software with source code that anyone can inspect, modify, and
enhance.

"Source code" is the part of software that most computer users don't ever see; it's the code
computer programmers can manipulate to change how a piece of software—a "program" or
"application"—works. Programmers who have access to a computer program's source code
can improve that program by adding features to it or fixing parts that don't always work
correctly.

What's the difference between open source software and


other types of software?
Some software has source code that only the person, team, or organization who created it—
and maintains exclusive control over it—can modify. People call this kind of software
"proprietary" or "closed source" software.

Only the original authors of proprietary software can legally copy, inspect, and alter that
software. And in order to use proprietary software, computer users must agree (usually by
signing a license displayed the first time they run this software) that they will not do anything
with the software that the software's authors have not expressly permitted. Microsoft Office
and Adobe Photoshop are examples of proprietary software.

Open source software is different. Its authors make its source code available to others who
would like to view that code, copy it, learn from it, alter it, or share it. LibreOffice and the
GNU Image Manipulation Program are examples of open source software.

As they do with proprietary software, users must accept the terms of a license when they use
open source software—but the legal terms of open source licenses differ dramatically from
those of proprietary licenses.

Open source licenses affect the way people can use, study, modify, and distribute software. In
general, open source licenses grant computer users permission to use open source software
for any purpose they wish. Some open source licenses—what some people call "copyleft"
licenses—stipulate that anyone who releases a modified open source program must also
release the source code for that program alongside it. Moreover, some open source licenses
stipulate that anyone who alters and shares a program with others must also share that
program's source code without charging a licensing fee for it.

2. Advantages of Open Source Software


Today open source software has become critical for almost every organization. Almost
everything requires open source software, be it telecommunication systems, inventory,
accounting, personal productivity applications, contact management and operating systems
amongst others. At Outsource2india, we have experienced and skilled software engineers
who can proficiently build a software system by using open source software. With our
expertise in java development, we can also develop application blocks. We also use our
system integration services to make sure that the new application that we create can be easily
integrated with your existing systems. Outsource open source software development to O2I
and benefit from high-quality services at a cost-effective price.

Open source software can have a major impact on your entire organization. There are several
advantages of using open source software. The following are a list of the advantages of
opting for open source software.

1. Lesser hardware costs


Since Linux and open source solutions are easily portable and compressed, it takes
lesser hardware power to carry out the same tasks when compared to the hardware
power it takes on servers, such as, Solaris, Windows or workstations. With this less
hardware power advantage, you can even use cheaper or older hardware and still get
the desired results.

2. High-quality software
Open source software is mostly high-quality software. When you use the open source
software, the source code is available. Most open source software are well-designed.
Open source software can also be efficiently used in coding. These reasons make open
source software an ideal choice for organizations.

3. No vendor lock-in
IT managers in organizations face constant frustration when dealing with vendor lock-
ins'. Lack of portability, expensive license fees and inability to customize software are
some of the other disadvantages. Using open source software gives you more freedom
and you can effectively address all these disadvantages.

4. Integrated management
By using open source software, you can benefit from integrated management. Open
source software uses technologies, such as, common information model (CIM) and
web based enterprise management (WBEM). These high-end technologies enable you
to integrate and combine server, application, service and workstation management.
This integration would result in efficient administration.

5. Simple license management


When you use open source software, you would no longer need to worry about
licenses. Open source software enables you to install it several times and also use it
from any location. You will be free from monitoring, tracking or counting license
compliance.

6. Lower software costs


Using open source software can help you minimize your expenses. You can save on
licensing fees and maintenance fees. The only expenses that you would encounter
would be expenditure for documentation, media and support.
7. Abundant support
You will get ample support when you use open source software. Open source support
is mostly freely available and can be easily accessed through online communities.
There are also many software companies that provide free online help and also varied
levels of paid support. Most organization who create open source software solutions
also provide maintenance and support.

8. Scaling and consolidating


Linux and open source software can be easily scaled. With varied options for
clustering, load balancing and open source applications, such as email and database,
you can enable your organization to either scale up and achieve higher growth or
consolidate and achieve more with less.

3.open source operating system?

Open Source operating systems are released under a license where the copyright holder
allows others to study, change as well as distribute the software to other people. This can be
done for any reason. The different open source operating system available in the market are −

Cosmos
This is an open source operating system written mostly in programming language C#. Its full
form is C# Open Source Managed Operating System. Till 2016, Cosmos did not intend to be
a fully fledged operating system but a system that allowed other developers to easily build
their own operating systems. It also hid the inner workings of the hardware from the
developers thus providing data abstraction.

FreeDOS
This was a free operating system developed for systems compatible with IBM PC computers.
FreeDOS provides a complete environment to run legacy software and other embedded
systems. It can booted from a floppy disk or USB flash drive as required. FreeDos is licensed
under the GNU General Public license and contains free and open source software. So there
is no license fees required for its distribution and changes to the system are permitted.

Genode
Genode is free as well as open source. It contains a microkernel layer and different user
components. It is one of the few open source operating systems not derived from a licenced
operating system such as Unix. Genode can be used as an operating system for computers,
tablets etc. as required. It is also used as a base for virtualisation, interprocess
communication, software development etc. as it has a small code system.

Ghost OS
This is a free, open source operating system developed for personal computers. It started as a
research project and developed to contain various advanced features like graphical user
interface, C library etc. The Ghost operating system features multiprocessing and
multitasking and is based on the Ghost Kernel. Most of the programming in Ghost OS is done
in C++.

ITS
The incompatible time-sharing system was developed by the MIT Artificial Intelligence
Library. It is principally a time sharing system. There is a remote login facility which allowed
guest users to informally try out the operating system and its features using ARPAnet. ITS
also gave out many new features that were unique at that time such as device independent
graphics terminal, virtual devices, inter machine file system access etc.

OSv
This was an operating system released in 2013. It was mainly focused on cloud computing
and was built to run on top of a virtual machine as a guest. This is the reason it doesn't
include drivers for bare hardware. In the OSv operating system, everything runs in the kernel
address space and there is no concept of a multi-user system.

Phantom OS
This is an operating system that is based on the concepts on persistent virtual memory and is
code oriented. It was mostly developed by Russian developers. Phantom OS is not based on
concepts of famous operating systems such as Unix. Its main goal is simplicity and
effectiveness in process management.

4. Introduction to LINUX?

Linux is a community of open-source Unix like operating systems that are based on the Linux
Kernel. It was initially released by Linus Torvalds on September 17, 1991. It is a free and
open-source operating system and the source code can be modified and distributed to anyone
commercially or noncommercially under the GNU General Public License.
Initially, Linux was created for personal computers and gradually it was used in other
machines like servers, mainframe computers, supercomputers, etc. Nowadays, Linux is also
used in embedded systems like routers, automation controls, televisions, digital video
recorders, video game consoles, smartwatches, etc. The biggest success of Linux is
Android(operating system) it is based on the Linux kernel that is running on smartphones and
tablets. Due to android Linux has the largest installed base of all general-purpose operating
systems. Linux is generally packaged in a Linux distribution.

Linux Distribution

Linux distribution is an operating system that is made up of a collection of software based on


Linux kernel or you can say distribution contains the Linux kernel and supporting libraries
and software. And you can get Linux based operating system by downloading one of the
Linux distributions and these distributions are available for different types of devices like
embedded devices, personal computers, etc. Around 600 + Linux Distributions are available
and some of the popular Linux distributions are:

 MX Linux
 Manjaro
 Linux Mint
 elementary
 Ubuntu
 Debian
 Solus
 Fedora
 openSUSE
 Deepin

Architecture of Linux

Linux architecture has the following components:

1. Kernel: Kernel is the core of the Linux based operating system. It virtualizes the
common hardware resources of the computer to provide each process with its virtual
resources. This makes the process seem as if it is the sole process running on the
machine. The kernel is also responsible for preventing and mitigating conflicts
between different processes. Different types of the kernel are:
o Monolithic Kernel
o Hybrid kernels
o Exo kernels
o Micro kernels
2. System Library: Isthe special types of functions that are used to implement the
functionality of the operating system.
3. Shell: It is an interface to the kernel which hides the complexity of the kernel’s
functions from the users. It takes commands from the user and executes the kernel’s
functions.
4. Hardware Layer: This layer consists all peripheral devices like RAM/ HDD/ CPU
etc.
5. System Utility: It provides the functionalities of an operating system to the user.
Advantages of Linux

 The main advantage of Linux, is it is an open-source operating system. This means


the source code is easily available for everyone and you are allowed to contribute,
modify and distribute the code to anyone without any permissions.
 In terms of security, Linux is more secure than any other operating system. It does not
mean that Linux is 100 percent secure it has some malware for it but is less vulnerable
than any other operating system. So, it does not require any anti-virus software.
 The software updates in Linux are easy and frequent.
 Various Linux distributions are available so that you can use them according to your
requirements or according to your taste.
 Linux is freely available to use on the internet.
 It has large community support.
 It provides high stability. It rarely slows down or freezes and there is no need to
reboot it after a short time.
 It maintain the privacy of the user.
 The performance of the Linux system is much higher than other operating systems. It
allows a large number of people to work at the same time and it handles them
efficiently.
 It is network friendly.
 The flexibility of Linux is high. There is no need to install a complete Linux suit; you
are allowed to install only required components.
 Linux is compatible with a large number of file formats.
 It is fast and easy to install from the web. It can also install on any hardware even on
your old computer system.
 It performs all tasks properly even if it has limited space on the hard disk.

Disadvantages of Linux

 It is not very user-friendly. So, it may be confusing for beginners.


 It has small peripheral hardware drivers as compared to windo

5. Linux advanced concepts?

1. 1. Linux ..some advancedconcepts :)


2. 2. The Linux File SystemDefault File System● EXT3● EXT4Other File Systems●
XFS● Reiser4● GFS● BTRFS
3. 3. Ext4 Enhancements● Large Filesystem support (1 EB)● Extends● Multi-block
allocator● Persistent pre-allocation● Delayed Allocation● Journal checksuming●
Faster file system checking● Sub-directory limit has been removed (32000)● Nano
second time stamps
4. 4. Users and Persmissions● Adding / Deleting / Modify users● Managing groups●
User variables● Environment variables● ldconfig
5. 5. Changing and Managing permissions The long version of a file listing (ls -l) will
display the file permissions: -rwxrwxr-x 1 rvdheij rvdheij 5224 Dec 30 03:22 hello -
rw-rw-r-- 1 rvdheij rvdheij 221 Dec 30 03:59 hello.c -rw-rw-r-- 1 rvdheij rvdheij 1514
Dec 30 03:59 hello.s drwxrwxr-x 7 rvdheij rvdheij 1024 Dec 31 14:52
posixuftPermissions Group Owner
6. 6. Interpreting File Permissions -rwxrwxrwx Other permissions Group permissions
Owner permissionsDirectory flag (d=directory; l=link)
7. 7. Changing and Managing permissions● chgrp● chown● chmod chmod 755 file #
Owner=rwx Group=r-x Other=r-x chmod 500 file2 # Owner=r-x Group=--- Other=---
chmod 644 file3 # Owner=rw- Group=r-- Other=r-- chmod +x file # Add execute
permission to file for all chmod o-r file # Remove read permission for others chmod
a+w file # Add write permission for everyone
8. 8. Basic System Administration● Monitoring the System ● memory ● disk space ●
processor● Load Average● Creating partitions manually and mount them (cli)●
System and Kernel update● Sharing files between Windows and Linux ● configuring
samba server
9. 9. Security● Network Security ● Iptables ● TCP Wrappers ● Service Level Security
● SELinux● Physical security
10. 10. Linux Kernel Subsystems
11. 11. Processes● User Mode● Kernel Mode● Mode Switch● Context Switch
12. 12. Manage Process● Kill Signals● Zombies Process● Orphan Process● Process
priority
13. 13. Linux Kernel Subsystems
14. 14. The Linux Kernel User commands includesexecutable programs and scripts User
Commands The shell interprets user Shellcommands. It is responsible for finding the
commands and Kernel File System starting their execution. Device Drivers
HardwareThe kernel manages the hardware resources for the rest of the system.
15. 15. Questions?Ask at www.iwillstudy.com/forum

6. The evolution of scheduling in Linux

By and large, by the year 2000, operating systems designers considered scheduling to
be a solved problem… (the) year 2004 brought an end to Dennard scaling, ushered in the
multicore era and made energy efficiency a top concern in the design of computer systems.
These events once again made schedulers interesting, but at the same time increasingly more
complicated and often broken.

Linux uses a Completely Fair Scheduling (CFS) algorithm, which is an implementation of


weighted fair queueing (WFQ). Imagine a single CPU system to start with: CFS time-slices
the CPU among running threads. There is a fixed time interval during which each thread in
the system must run at least once. This interval is divided into timeslices that are allocated to
threads according to their weights.

A thread’s weight is essentially its priority, or niceness in UNIX parlance. Threads with
lower niceness have higher weights and vice versa.

A running thread accumulates vruntime (runtime / weight). When a thread’s vruntime


exceeds its assigned timeslice it will be pre-empted.

Threads are organized in a runqueue, implemented as a red-black tree, in which the threads
are sorted in the increasing order of their vruntime. When a CPU looks for a new thread to
run it picks the leftmost node in the red-black tree, which contains the thread with the
smallest vruntime.

So far so good, but now we have to talk about multi-core systems…

Firstly we need per-core runqueues so that context switches can be fast. Now we have a new
problem of balancing work across multiple runqueues.

Consider a dual-core system with two runqueues that are not balanced.Suppose that one
queue has one low-priority thread and another has ten high-priority threads. If each core
looked for work only in its local runqueue, then high-priority threads would get a lot less
CPU time than the low-priority thread, which is not what we want. We could have each core
checknot only its runqueue but also the queues of other cores,but this would defeat the
purpose of per-core runqueues. Therefore, what Linux and most other schedulers do is
periodically run a load-balancing algorithm that will keep the queues roughly balanced.

7. Introduction to 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 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.
 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).
 MySQL is customizable. The open-source GPL license allows programmers to
modify the MySQL software to fit their own specific environments.

8. How to Create New MySQL User and explain?


1. Before you can create a new MySQL user, you need to open a terminal window and launch
the MySQL shell as the root user. To do so, enter the following command:

sudo mysql –u root –p

2. Type in the root password for this account and press Enter.

The prompt should change to show that you are in the mysql> shell.

3. Next, create a new MySQL user with:

CREATE USER 'username' IDENTIFIED BY 'password';

Replace username and password with a username and password of your choice.

Alternatively, you can set up a user by specifying the machine hosting the database.
 If you are working on the machine with MySQL, use username@localhost to define
the user.
 If you are connecting remotely, use username@ip_address, and replace ip_address
with the actual address of the remote system hosting MySQL.

Therefore, the command will be:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

or

CREATE USER 'username'@'ip_address' IDENTIFIED BY 'password';

You can also create a user that can connect from any machine with the command:

CREATE USER 'username'@'%' IDENTIFIED BY 'password';

9. Starting and Terminating mysql and explain?

Problem
You want to start and stop the mysql program.

Solution
Invoke mysql from your command prompt to start it, specifying any connection parameters
that may be necessary. To leave mysql, use a QUIT statement.

Discussion
To start the mysql program, try just typing its name at your command-line prompt. If mysql
starts up correctly, you’ll see a short message, followed by a mysql> prompt that indicates the
program is ready to accept queries. To illustrate, here’s what the welcome message looks like
(to save space, I won’t show it in any further examples):

% mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18427 to server version: 3.23.51-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

If mysql tries to start but exits immediately with an “access denied” message, you’ll need to
specify connection parameters. The most commonly needed parameters are the host to
connect to (the host where the MySQL server runs), your MySQL username, and a password.
For example:

% mysql -h localhost -p -u cbuser


Enter password: cbpass
In general, I’ll show mysql commands in examples with no connection parameter options. I
assume that you’ll supply any parameters that you need, either on the command line, or in an
option file (Recipe 1.5) so that you don’t have to type them each time you invoke mysql.

If you don’t have a MySQL username and password, you need to obtain permission to use the
MySQL server, as described earlier in Recipe 1.2.

The syntax and default values for the connection parameter options are shown in the
following table. These options have both a single-dash short form and a double-dash long
form.

Parameter type Option syntax forms Default value


Hostname -h hostname--host=hostname localhost
Username -u username--user=username Your login name
Password -p--password None

As the table indicates, there is no default password. To supply one, use --password or -p,
then enter your password when mysql prompts you for it:

% mysql -pEnter password: ← enter your password here

If you like, you can specify the password directly on the command line by using either -
ppassword (note that there is no space after the -p) or --password=password. I don’t
recommend doing this on a multiple-user machine, because the password may be visible
momentarily to other users who are running tools such as ps that report process information.

If you get an error message that mysql cannot be found or is an invalid command when you
try to invoke it, that means your command interpreter doesn’t know where mysql is installed.
See Recipe 1.8.

To terminate a mysql session, issue a QUIT statement:

mysql> QUIT

You can also terminate the session by issuing an EXIT statement or (under Unix) by typing
Ctrl-D.

The way you specify connection parameters for mysql also applies to other MySQL
programs such as mysqldump and mysqladmin. For example, some of the actions that
mysqladmin can perform are available only to the MySQL root account, so you need to
specify name and password options for that user:

% mysqladmin -p -u root shutdown


Enter password:

10. Recordes selection technology?


This chapter focuses on the SELECT statement that is used for retrieving information from a
database. It provides some essential background that shows various ways you can use SELECT
to tell MySQL what you want to see. You should find the chapter helpful if your SQL
background is limited or if you want to find out about the MySQL-specific extensions to
SELECT syntax. However, there are so many ways to write SELECT queries that we’ll
necessarily touch on just a few. You may wish to consult the MySQL Reference Manual or a
MySQL text for more information about the syntax of SELECT, as well as the functions and
operators that you can use for extracting and manipulating data.

SELECT gives you control over several aspects of record retrieval:

 Which table to use


 Which columns to display from the table
 What names to give the columns
 Which rows to retrieve from the table
 How to sort the rows

Many useful queries are quite simple and don’t specify all those things. For example, some
forms of SELECT don’t even name a table—a fact used in Recipe 1.32, which discusses how
to use mysql as a calculator. Other non-table-based queries are useful for purposes such as
checking what version of the server you’re running or the name of the current database:

11. Working with Strings?


Like most data types, strings can be compared for equality or inequality or relative ordering.
However, strings have some additional properties to consider:

 Strings can be case sensitive (or not), which can affect the outcome of string
operations.
 You can compare entire strings, or just parts of them by extracting substrings.
 You can apply pattern-matching operations to look for strings that have a certain
structure.

This chapter discusses several useful string operations you can perform, including how to
account for whether or not strings are case sensitive.

The following table, metal, is used in several sections of this chapter:

mysql> SELECT * FROM metal;


+----------+
| name |
+----------+
| copper |
| gold |
| iron |
| lead |
| mercury |
| platinum |
| silver |
| tin |
+----------+

The table is very simple, containing only a single string column:

CREATE TABLE metal


(
name VARCHAR(20)
);

You can create the table using the metal.sql script in the tables directory of the recipes
distribution.
Types of Strings
MySQL can operate on regular strings or binary strings. “Binary” in this context has little to
do with the presence of non-ASCII values, so it’s useful right at the outset to make a
distinction:

 Binary data may contain bytes that lie outside the usual range of printable ASCII
characters.
 A binary string in MySQL is one that MySQL treats as case sensitive in comparisons.
For binary strings, the characters A and a are considered different. For non-binary
strings, they’re considered the same.

A binary column type is one that contains binary strings. Some of MySQL’s column types are
binary (case sensitive) and others are not, as illustrated here:

Column type Binary/case sensitive


CHAR, VARCHAR No
CHAR BINARY, VARCHAR BINARY Yes
TEXT No
BLOB Yes
ENUM, SET No

12. ADDDATE(date,INTERVAL expr unit),


ADDDATE(expr,days)
When invoked with the INTERVAL form of the second argument, ADDDATE() is a
synonym for DATE_ADD(). The related function SUBDATE() is a synonym for
DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for
DATE_ADD().

mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY);


+---------------------------------------------------------+
| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY);


+---------------------------------------------------------+
| ADDDATE('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

When invoked with the days form of the second argument, MySQL treats it as an integer
number of days to be added to expr.

mysql> SELECT ADDDATE('1998-01-02', 31);


+---------------------------------------------------------+
| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

ADDTIME(expr1,expr2)
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime
expression and expr2 is a time expression.

mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999','1 1:1:1.000002');


+---------------------------------------------------------+
| DATE_ADD('1997-12-31 23:59:59.999999','1 1:1:1.000002') |
+---------------------------------------------------------+
| 1998-01-02 01:01:01.000001 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

CONVERT_TZ(dt,from_tz,to_tz)
This converts a datetime value dt from the time zone given by from_tz to the time zone given
by to_tz and returns the resulting value. This function returns NULL if the arguments are
invalid.

mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');


+---------------------------------------------------------+
| CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') |
+---------------------------------------------------------+
| 2004-01-01 13:00:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');


+---------------------------------------------------------+
| CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') |
+---------------------------------------------------------+
| 2004-01-01 22:00:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending
on whether the function is used in a string or numeric context.

mysql> SELECT CURDATE();


+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 1997-12-15 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CURDATE() + 0;


+---------------------------------------------------------+
| CURDATE() + 0 |
+---------------------------------------------------------+
| 19971215 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
CURRENT_DATE and CURRENT_DATE()
CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE()

CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or numeric context. The value is expressed in the
current time zone.

mysql> SELECT CURTIME();


+---------------------------------------------------------+
| CURTIME() |
+---------------------------------------------------------+
| 23:50:26 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CURTIME() + 0;


+---------------------------------------------------------+
| CURTIME() + 0 |
+---------------------------------------------------------+
| 235026 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

CURRENT_TIME and CURRENT_TIME()


CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME().

CURRENT_TIMESTAMP and
CURRENT_TIMESTAMP()
CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW().

DATE(expr)
Extracts the date part of the date or datetime expression expr.

mysql> SELECT DATE('2003-12-31 01:02:03');


+---------------------------------------------------------+
| DATE('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 2003-12-31 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the other.
expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are
used in the calculation.

mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');


+---------------------------------------------------------+
| DATEDIFF('1997-12-31 23:59:59','1997-12-30') |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DATE_ADD(date,INTERVAL expr unit),


DATE_SUB(date,INTERVAL expr unit)
These functions perform date arithmetic. date is a DATETIME or DATE value specifying the
starting date. expr is an expression specifying the interval value to be added or subtracted
from the starting date. expr is a string; it may start with a '-' for negative intervals. unit is a
keyword indicating the units in which the expression should be interpreted.

The INTERVAL keyword and the unit specifier are not case sensitive.

The following table shows the expected form of the expr argument for each unit value;

unit Value ExpectedexprFormat


MICROSECOND MICROSECONDS
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND 'MINUTES.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MICROSECOND 'HOURS.MICROSECONDS'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_MICROSECOND 'DAYS.MICROSECONDS'
DAY_SECOND 'DAYS HOURS:MINUTES:SECONDS'
DAY_MINUTE 'DAYS HOURS:MINUTES'
DAY_HOUR 'DAYS HOURS'
YEAR_MONTH 'YEARS-MONTHS'

The values QUARTER and WEEK are available beginning with MySQL 5.0.0.

mysql> SELECT DATE_ADD('1997-12-31 23:59:59',


-> INTERVAL '1:1' MINUTE_SECOND);
+---------------------------------------------------------+
| DATE_ADD('1997-12-31 23:59:59', INTERVAL... |
+---------------------------------------------------------+
| 1998-01-01 00:01:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR);


+---------------------------------------------------------+
| DATE_ADD('1999-01-01', INTERVAL 1 HOUR) |
+---------------------------------------------------------+
| 1999-01-01 01:00:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DATE_FORMAT(date,format)
Formats the date value according to the format string.

The following specifiers may be used in the format string. The .%. character is required
before format specifier characters.

S. No. Specifier & Description


%a
1
Abbreviated weekday name (Sun..Sat)
%b
2
Abbreviated month name (Jan..Dec)
%c
3
Month, numeric (0..12)
%D
4
Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)
%d
5
Day of the month, numeric (00..31)
%e
6
Day of the month, numeric (0..31)
%f
7
Microseconds (000000..999999)
%H
8
Hour (00..23)
%h
9
Hour (01..12)
%I
10
Hour (01..12)
%i
11
Minutes, numeric (00..59)
%j
12
Day of year (001..366)
%k
13
Hour (0..23)
%l
14
Hour (1..12)
%M
15
Month name (January..December)
%m
16
Month, numeric (00..12)
%p
17
AM or PM
%r
18
Time, 12-hour (hh:mm:ss followed by AM or PM)
%S
19
Seconds (00..59)
%s
20
Seconds (00..59)
%T
21
Time, 24-hour (hh:mm:ss)
%U
22
Week (00..53), where Sunday is the first day of the week
%u
23
Week (00..53), where Monday is the first day of the week
%V
24
Week (01..53), where Sunday is the first day of the week; used with %X
%v
25
Week (01..53), where Monday is the first day of the week; used with %x
%W
26
Weekday name (Sunday..Saturday)
%w
27
Day of the week (0 = Sunday..6 = Saturday)
%X
28
Year for the week where Sunday is the first day of the week, numeric, four digits;
used with %V
%x
29
Year for the week, where Monday is the first day of the week, numeric, four digits;
used with %v
%Y
30
Year, numeric, four digits
%y
31
Year, numeric (two digits)
%
32
A literal .%. character
%x
33
x, for any.x. not listed above
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
+---------------------------------------------------------+
| DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') |
+---------------------------------------------------------+
| Saturday October 1997 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00'


-> '%H %k %I %r %T %S %w');
+---------------------------------------------------------+
| DATE_FORMAT('1997-10-04 22:23:00....... |
+---------------------------------------------------------+
| 22 22 10 10:23:00 PM 22:23:00 00 6 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DATE_SUB(date,INTERVAL expr unit)


This is similar to DATE_ADD() function.

DAY(date)
DAY() is a synonym for DAYOFMONTH().

DAYNAME(date)
Returns the name of the weekday for date.

mysql> SELECT DAYNAME('1998-02-05');


+---------------------------------------------------------+
| DAYNAME('1998-02-05') |
+---------------------------------------------------------+
| Thursday |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.

mysql> SELECT DAYOFMONTH('1998-02-03');


+---------------------------------------------------------+
| DAYOFMONTH('1998-02-03') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index
values correspond to the ODBC standard.

mysql> SELECT DAYOFWEEK('1998-02-03');


+---------------------------------------------------------+
| DAYOFWEEK('1998-02-03') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.

mysql> SELECT DAYOFYEAR('1998-02-03');


+---------------------------------------------------------+
| DAYOFYEAR('1998-02-03') |
+---------------------------------------------------------+
| 34 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

EXTRACT(unit FROM date)


The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or
DATE_SUB(), but extracts parts from the date rather than performing date arithmetic.

mysql> SELECT EXTRACT(YEAR FROM '1999-07-02');


+---------------------------------------------------------+
| EXTRACT(YEAR FROM '1999-07-02') |
+---------------------------------------------------------+
| 1999 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03');


+---------------------------------------------------------+
| EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03') |
+---------------------------------------------------------+
| 199907 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

FROM_DAYS(N)
Given a day number N, returns a DATE value.

mysql> SELECT FROM_DAYS(729669);


+---------------------------------------------------------+
| FROM_DAYS(729669) |
+---------------------------------------------------------+
| 1997-10-07 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

Use FROM_DAYS() with caution on old dates. It is not intended for use with values that
precede the advent of the Gregorian calendar (1582).

FROM_UNIXTIME(unix_timestamp)
FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD
HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used
in a string or numeric context. The value is expressed in the current time zone.
unix_timestamp is an internal timestamp value such as is produced by the
UNIX_TIMESTAMP() function.

If format is given, the result is formatted according to the format string, which is used the
same way as listed in the entry for the DATE_FORMAT() function.

mysql> SELECT FROM_UNIXTIME(875996580);


+---------------------------------------------------------+
| FROM_UNIXTIME(875996580) |
+---------------------------------------------------------+
| 1997-10-04 22:23:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

HOUR(time)
Returns the hour for the time. The range of the return value is 0 to 23 for time-of-day values.
However, the range of TIME values actually is much larger, so HOUR can return values
greater than 23.

mysql> SELECT HOUR('10:05:03');


+---------------------------------------------------------+
| HOUR('10:05:03') |
+---------------------------------------------------------+
| 10 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the
month. Returns NULL if the argument is invalid.

mysql> SELECT LAST_DAY('2003-02-05');


+---------------------------------------------------------+
| LAST_DAY('2003-02-05') |
+---------------------------------------------------------+
| 2003-02-28 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

LOCALTIME and LOCALTIME()


LOCALTIME and LOCALTIME() are synonyms for NOW().

LOCALTIMESTAMP and LOCALTIMESTAMP()


LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW().

MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. dayofyear must be greater than 0 or the
result is NULL.

mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32);


+---------------------------------------------------------+
| MAKEDATE(2001,31), MAKEDATE(2001,32) |
+---------------------------------------------------------+
| '2001-01-31', '2001-02-01' |
+---------------------------------------------------------+
1 row in set (0.00 sec)

MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute and second arguments.

mysql> SELECT MAKETIME(12,15,30);


+---------------------------------------------------------+
| MAKETIME(12,15,30) |
+---------------------------------------------------------+
| '12:15:30' |
+---------------------------------------------------------+
1 row in set (0.00 sec)

MICROSECOND(expr)
Returns the microseconds from the time or datetime expression expr as a number in the range
from 0 to 999999.

mysql> SELECT MICROSECOND('12:00:00.123456');


+---------------------------------------------------------+
| MICROSECOND('12:00:00.123456') |
+---------------------------------------------------------+
| 123456 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MINUTE(time)
Returns the minute for time, in the range 0 to 59.

mysql> SELECT MINUTE('98-02-03 10:05:03');


+---------------------------------------------------------+
| MINUTE('98-02-03 10:05:03') |
+---------------------------------------------------------+
| 5 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

MONTH(date)
Returns the month for date, in the range 0 to 12.

mysql> SELECT MONTH('1998-02-03')


+---------------------------------------------------------+
| MONTH('1998-02-03') |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

MONTHNAME(date)
Returns the full name of the month for date.

mysql> SELECT MONTHNAME('1998-02-05');


+---------------------------------------------------------+
| MONTHNAME('1998-02-05') |
+---------------------------------------------------------+
| February |
+---------------------------------------------------------+
1 row in set (0.00 sec)

NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();


+---------------------------------------------------------+
| NOW() |
+---------------------------------------------------------+
| 1997-12-15 23:50:26 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

PERIOD_ADD(P,N)
Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the
format YYYYMM. Note that the period argument P is not a date value.

mysql> SELECT PERIOD_ADD(9801,2);


+---------------------------------------------------------+
| PERIOD_ADD(9801,2) |
+---------------------------------------------------------+
| 199803 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2. P1 and P2 should be in the format
YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values.

mysql> SELECT PERIOD_DIFF(9802,199703);


+---------------------------------------------------------+
| PERIOD_DIFF(9802,199703) |
+---------------------------------------------------------+
| 11 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4.

mysql> SELECT QUARTER('98-04-01');


+---------------------------------------------------------+
| QUARTER('98-04-01') |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

SECOND(time)
Returns the second for time, in the range 0 to 59.

mysql> SELECT SECOND('10:05:03');


+---------------------------------------------------------+
| SECOND('10:05:03') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes, and seconds, as a value in
'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or
numeric context.

mysql> SELECT SEC_TO_TIME(2378);


+---------------------------------------------------------+
| SEC_TO_TIME(2378) |
+---------------------------------------------------------+
| 00:39:38 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string
format. STR_TO_DATE() returns a DATETIME value if the format string contains both date
and time parts, or a DATE or TIME value if the string contains only date or time parts.

mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');


+---------------------------------------------------------+
| STR_TO_DATE('04/31/2004', '%m/%d/%Y') |
+---------------------------------------------------------+
| 2004-04-31 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

SUBDATE(date,INTERVAL expr unit) and


SUBDATE(expr,days)
When invoked with the INTERVAL form of the second argument, SUBDATE() is a
synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the
discussion for DATE_ADD().

mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);


+---------------------------------------------------------+
| DATE_SUB('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1997-12-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY);


+---------------------------------------------------------+
| SUBDATE('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1997-12-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

SUBTIME(expr1,expr2)
SUBTIME() returns expr1 . expr2 expressed as a value in the same format as expr1. expr1 is
a time or datetime expression, and expr2 is a time.

mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999',


-> '1 1:1:1.000002');
+---------------------------------------------------------+
| SUBTIME('1997-12-31 23:59:59.999999'... |
+---------------------------------------------------------+
| 1997-12-30 22:58:58.999997 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context.
mysql> SELECT SYSDATE();
+---------------------------------------------------------+
| SYSDATE() |
+---------------------------------------------------------+
| 2006-04-12 13:47:44 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a string.

mysql> SELECT TIME('2003-12-31 01:02:03');


+---------------------------------------------------------+
| TIME('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 01:02:03 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIMEDIFF(expr1,expr2)
TIMEDIFF() returns expr1 . expr2 expressed as a time value. expr1 and expr2 are time or
date-and-time expressions, but both must be of the same type.

mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001',


-> '1997-12-30 01:01:01.000002');
+---------------------------------------------------------+
| TIMEDIFF('1997-12-31 23:59:59.000001'..... |
+---------------------------------------------------------+
| 46:58:57.999999 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime expression expr as a
datetime value. With two arguments, it adds the time expression expr2 to the date or datetime
expression expr1 and returns the result as a datetime value.

mysql> SELECT TIMESTAMP('2003-12-31');


+---------------------------------------------------------+
| TIMESTAMP('2003-12-31') |
+---------------------------------------------------------+
| 2003-12-31 00:00:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIMESTAMPADD(unit,interval,datetime_expr)
Adds the integer expression interval to the date or datetime expression datetime_expr. The
unit for interval is given by the unit argument, which should be one of the following values:
FRAC_SECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or
YEAR.
The unit value may be specified using one of keywords as shown, or with a prefix of
SQL_TSI_. For example, DAY and SQL_TSI_DAY both are legal.

mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02');


+---------------------------------------------------------+
| TIMESTAMPADD(MINUTE,1,'2003-01-02') |
+---------------------------------------------------------+
| 2003-01-02 00:01:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns the integer difference between the date or datetime expressions datetime_expr1 and
datetime_expr2. The unit for the result is given by the unit argument. The legal values for
unit are the same as those listed in the description of the TIMESTAMPADD() function.

mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');


+---------------------------------------------------------+
| TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') |
+---------------------------------------------------------+
| 3 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIME_FORMAT(time,format)
This is used like the DATE_FORMAT() function, but the format string may contain format
specifiers only for hours, minutes, and seconds.

If the time value contains an hour part that is greater than 23, the %H and %k hour format
specifiers produce a value larger than the usual range of 0..23. The other hour format
specifiers produce the hour value modulo 12.

mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');


+---------------------------------------------------------+
| TIME_FORMAT('100:00:00', '%H %k %h %I %l') |
+---------------------------------------------------------+
| 100 100 04 04 4 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TIME_TO_SEC(time)
Returns the time argument, converted to seconds.

mysql> SELECT TIME_TO_SEC('22:23:00');


+---------------------------------------------------------+
| TIME_TO_SEC('22:23:00') |
+---------------------------------------------------------+
| 80580 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

TO_DAYS(date)
Given a date, returns a day number (the number of days since year 0).

mysql> SELECT TO_DAYS(950501);


+---------------------------------------------------------+
| TO_DAYS(950501) |
+---------------------------------------------------------+
| 728779 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
If called with no argument, returns a UNIX timestamp (seconds since '1970-01-01 00:00:00'
UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it
returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a
DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD
or YYYYMMDD.

mysql> SELECT UNIX_TIMESTAMP();


+---------------------------------------------------------+
| UNIX_TIMESTAMP() |
+---------------------------------------------------------+
| 882226357 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');


+---------------------------------------------------------+
| UNIX_TIMESTAMP('1997-10-04 22:23:00') |
+---------------------------------------------------------+
| 875996580 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

UTC_DATE, UTC_DATE()
Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or numeric context.

mysql> SELECT UTC_DATE(), UTC_DATE() + 0;


+---------------------------------------------------------+
| UTC_DATE(), UTC_DATE() + 0 |
+---------------------------------------------------------+
| 2003-08-14, 20030814 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

UTC_TIME, UTC_TIME()
Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or numeric context.

mysql> SELECT UTC_TIME(), UTC_TIME() + 0;


+---------------------------------------------------------+
| UTC_TIME(), UTC_TIME() + 0 |
+---------------------------------------------------------+
| 18:07:53, 180753 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

UTC_TIMESTAMP, UTC_TIMESTAMP()
Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context.

mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0;


+---------------------------------------------------------+
| UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0 |
+---------------------------------------------------------+
| 2003-08-14 18:08:04, 20030814180804 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

WEEK(date[,mode])
This function returns the week number for date. The two-argument form of WEEK() allows
you to specify whether the week starts on Sunday or Monday and whether the return value
should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the
value of the default_week_format system variable is used

Mode First Day of week Range Week 1 is the first week.


0 Sunday 0-53 with a Sunday in this year
1 Monday 0-53 with more than 3 days this year
2 Sunday 1-53 with a Sunday in this year
3 Monday 1-53 with more than 3 days this year
4 Sunday 0-53 with more than 3 days this year
5 Monday 0-53 with a Monday in this year
6 Sunday 1-53 with more than 3 days this year
7 Monday 1-53 with a Monday in this year
mysql> SELECT WEEK('1998-02-20');
+---------------------------------------------------------+
| WEEK('1998-02-20') |
+---------------------------------------------------------+
| 7 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday).

mysql> SELECT WEEKDAY('1998-02-03 22:23:00');


+---------------------------------------------------------+
| WEEKDAY('1998-02-03 22:23:00') |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.
WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).

mysql> SELECT WEEKOFYEAR('1998-02-20');


+---------------------------------------------------------+
| WEEKOFYEAR('1998-02-20') |
+---------------------------------------------------------+
| 8 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.

mysql> SELECT YEAR('98-02-03');


+---------------------------------------------------------+
| YEAR('98-02-03') |
+---------------------------------------------------------+
| 1998 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

YEARWEEK(date), YEARWEEK(date,mode)
Returns year and week for a date. The mode argument works exactly like the mode argument
to WEEK(). The year in the result may be different from the year in the date argument for the
first and the last week of the year.

mysql> SELECT YEARWEEK('1987-01-01');


+---------------------------------------------------------+
| YEAR('98-02-03')YEARWEEK('1987-01-01') |
+---------------------------------------------------------+
| 198653 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

13. SORTING QUERY RESULTS?

We have seen the SQL SELECT command to fetch data from a MySQL table. When you
select rows, the MySQL server is free to return them in any order, unless you instruct it
otherwise by saying how to sort the result. But, you sort a result set by adding an ORDER
BY clause that names the column or columns which you want to sort.

Syntax

The following code block is a generic SQL syntax of the SELECT command along with the
ORDER BY clause to sort the data from a MySQL table.

SELECT field1, field2,...fieldN table_name1, table_name2...


ORDER BY field1, [field2...] [ASC [DESC]]

 You can sort the returned result on any field, if that field is being listed out.
 You can sort the result on more than one field.
 You can use the keyword ASC or DESC to get result in ascending or descending
order. By default, it's the ascending order.
 You can use the WHERE...LIKE clause in the usual way to put a condition.

Using ORDER BY clause at the Command Prompt


This will use the SQL SELECT command with the ORDER BY clause to fetch data from the
MySQL table – tutorials_tbl.

Example

Try out the following example, which returns the result in an ascending order.

root@host# mysql -u root -p password;


Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl ORDER BY tutorial_author ASC
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 2 | Learn MySQL | Abdul S | 2007-05-24 |
| 1 | Learn PHP | John Poul | 2007-05-24 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-06 |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.42 sec)

mysql>

Verify all the author names that are listed out in the ascending order.

Using ORDER BY clause inside a PHP Script


You can use a similar syntax of the ORDER BY clause into the PHP function –
mysql_query(). This function is used to execute the SQL command and later another PHP
function mysql_fetch_array() can be used to fetch all the selected data.

Example

Try out the following example, which returns the result in a descending order of the tutorial
authors.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date
FROM tutorials_tbl
ORDER BY tutorial_author DESC';

mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not get data: ' . mysql_error());
}

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {


echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ".
"Submission Date : {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);

14. PHP | Introduction and explain?


The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side
scripting language designed specifically for web development. It is open-source which means
it is free to download and use. It is very simple to learn and use. The files have the extension
“.php”.

Rasmus Lerdorf inspired the first version of PHP and participating in the later versions. It is
an interpreted language and it does not require a compiler.

 PHP code is executed in the server.


 It can be integrated with many databases such as Oracle, Microsoft SQL Server,
MySQL, PostgreSQL, Sybase, Informix.
 It is powerful to hold a content management system like WordPress and can be used
to control user access.
 It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others.
 Websites like www.facebook.com, www.yahoo.com are also built on PHP.
 One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.
 The thing that differentiates PHP from the client-side language like HTML is, PHP
codes are executed on the server whereas HTML codes are directly rendered on the
browser. PHP codes are first executed on the server and then the result is returned to
the browser.
 The only information that the client or browser knows is the result returned after
executing the PHP script on the server and not the actual PHP codes present in the
PHP file. Also, PHP files can support other client-side scripting languages like CSS
and JavaScript.

Other characteristics of PHP are as follows.

 Simple and fast


 Efficient
 Secured
 Flexible
 Cross-platform, it works with major operating systems like Windows, Linux, MacOS.

16. PHP - Environment and explain?


In order to develop and run PHP Web pages three vital components need to be installed on
your computer system.
 Web Server − PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely
available Apache Server. Download Apache for free here −
https://httpd.apache.org/download.cgi
 Database − PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database. Download
MySQL for free here − https://www.mysql.com/downloads/
 PHP Parser − In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser. This tutorial will guide
you how to install PHP parser on your computer.

PHP Parser Installation


Before you proceed it is important to make sure that you have proper environment setup on
your machine to develop your web programs using PHP.

Type the following address into your browser's address box.

http://127.0.0.1/info.php

If this displays a page showing your PHP installation related information then it means you
have PHP and Webserver installed properly. Otherwise you have to follow given procedure
to install PHP on your computer.

This section will guide you to install and configure PHP over the following four platforms −

 PHP Installation on Linux or Unix with Apache


 PHP Installation on Mac OS X with Apache
 PHP Installation on Windows NT/2000/XP with IIS
 PHP Installation on Windows NT/2000/XP with Apache

Apache Configuration

If you are using Apache as a Web Server then this section will guide you to edit Apache
Configuration Files.

Just Check it here − PHP Configuration in Apache Server

PHP.INI File Configuration

The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's
functionality.

Just Check it here − PHP.INI File Configuration

17. PHP - Variable And DataTypes


The main way to store information in the middle of a PHP program is by using a
variable.
Here are the most important things to know about variables in PHP.

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
 PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables −

 Integers − are whole numbers, without a decimal point, like 4195.


 Doubles − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.
 Strings − are sequences of characters, like 'PHP supports string operations.'
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up both
other kinds of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to PHP
(such as database connections).

The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.

We will explain only simple data type in this chapters. Array and Objects will be explained
separately.

Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so −

$int_var = 12345;
$another_int = -12345 + 12345;

Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals
have a leading 0x.

For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code −

Live Demo

<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;

print("$many + $many_2 = $few <br>");


?>

It produces the following browser output −

2.28888 + 2.21112 = 4.5

Boolean
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so −

if (TRUE)
print("This will always print<br>");

else
print("This will never print<br>");

Interpreting other types as Booleans

Here are the rules for determine the "truth" of any value not already of the Boolean type −

 If the value is a number, it is false if exactly equal to zero and true otherwise.
 If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been
assigned a value.
 Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
 Don't use double as Booleans.

Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this −

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −

$my_var = null;

A variable that has been assigned NULL has the following properties −

 It evaluates to FALSE in a Boolean context.


 It returns FALSE when tested with IsSet() function.

Strings
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string

$string_1 = "This is a string in double quotes";


$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.

Live Demo

<?php
$variable = "name";
$literally = 'My $variable will not print!';

print($literally);
print "<br>";

$literally = "My $variable will print!";


print($literally);
?>

This will produce following result −

My $variable will not print!


My name will print

There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −

 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their
values.
The escape-sequence replacements are −

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

Here Document

You can assign multiple lines to a single string variable using here document −

Live Demo

<?php
$channel =<<<_XML_

<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/ </link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;

echo <<<END
This uses the "here document" syntax to output multiple lines with
variable
interpolation. Note that the here document terminator must appear on a
line with
just a semicolon. no extra whitespace!

END;

print $channel;
?>

This will produce following result −

This uses the "here document" syntax to output


multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!

<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>

Variable Scope
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −

 Local variables
 Function parameters
 Global variables
 Static variables

Variable Naming
Rules for naming a variable is −

 Variable names must begin with a letter or underscore character.


 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . &

18. PHP Functions?

A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better understanding of
how functions work. Suppose the boss wants his employee to calculate the annual budget. So
how will this process complete? The employee will take information about the statics from
the boss, performs calculations and calculate the budget and shows the result to his boss.
Functions works in a similar manner. They take informations as parameter, executes a block
of statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:

 Built-in functions : PHP provides us with huge collection of built-in library


functions. These functions are already coded and stored in form of functions. To use
those we just need to call them as per our requirement like, var_dump, fopen(),
print_r(), gettype() and so on.
 User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.

Why should we use functions?

 Reusability: If we have a common code that we would like to use at various parts of
a program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program
 Easier error detection: Since, our code is divided into functions, we can easily
detect in which function, the error could lie and fix them fast and easily.
 Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.

Creating a Function

While creating a user defined function we need to keep few things in mind:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or
underscore.
5. A function name is not case-sensitive.

Syntax:

function function_name(){
executable code;
}

Example:

<?php

function funcGeek()
{
echo "This is Geeks for Geeks";
}

// Calling the function


funcGeek();

?>

Output:

This is Geeks for Geeks

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are called parameters. These
are used to hold the values executable during runtime. A user is free to take in as many
parameters as he wants, separated with a comma(,) operator. These parameters are used to
accept inputs during runtime. While passing the values like during a function call, they are
called arguments. An argument is a value passed to a function and a parameter is used to hold
those arguments. In common term, both parameter and argument mean the same. We need to
keep in mind that for every parameter, we need to pass its corresponding argument.
Syntax:

function function_name($first_parameter, $second_parameter) {


executable code;
}

Example:

<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
// Calling the function
// Passing three arguments
proGeek(2, 3, 5);

?>

Output:

The product is 30

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:

<?php

// function with default parameter


function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}

// Calling the function


defGeek("Ram", 15);

// In this call, the default value 12


// will be considered
defGeek("Adam");

?>

Output:

Ram is 15 years old


Adam is 12 years old

In the above example, the parameter $num has a default value 12, if we do not pass any value
for this parameter in a function call then this default value 12 will be considered. Also the
parameter $str has no default value , so it is compulsory.

Returning Values from Functions

Functions can also return values to the part of program from where it is called. The return
keyword is used to return value back to the part of program, from where it was called. The
returning value may be of any type including the arrays and objects. The return statement also
marks the end of the function and stops the execution after that and returns the value.
Example:
<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product


}

// storing the returned value


$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";

?>

Output:

The product is 30

Parameter passing to Functions

PHP allows us two ways in which an argument can be passed into a function:

 Pass by Value: On passing arguments using pass by value, the value of the argument
gets changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an argument.
 Pass by Reference: On passing arguments as pass by reference, the original value is
passed. Therefore, the original value gets altered. In pass by reference we actually
pass the address of the value, where it is stored using ampersand sign(&).

Example:

<?php

// pass by value
function valGeek($num) {
$num += 2;
return $num;
}

// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}

$n = 10;

valGeek($n);
echo "The original value is still $n \n";

refGeek($n);
echo "The original value changes to $n";

?>

Output:

The original value is still 10


The original value changes to 2

19. PHP Operators


 Difficulty Level : Medium
 Last Updated : 11 Feb, 2019

Operators are used to perform operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them and gives a
result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1
and 2, performs addition operation on them to give 3.
Just like any other programming language, PHP also supports various types of operations like
the arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc),
Increment/Decrement Operations etc. Thus, PHP provides us with many operators to perform
such operations on various operands or variables or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are the various groups
of operators:

 Arithmetic Operators
 Logical or Relational Operators
 Comparison Operators
 Conditional or Ternary Operators
 Assignment Operators
 Spaceship Operators (Introduced in PHP 7)
 Array Operators
 Increment/Decrement Operators
 String Operators

Let us now learn about each of these operators in details:

Arithmetic Operators

The arithmetic operators are use to perform simple mathematical operations like addition,
subtraction, multiplication etc. Below is the list of arithmetic operators along with there
syntax and operations, that PHP provides us:

Operator Name Syntax Operation


+ Addition $x + $y Sum the operands
– Subtraction $x – $y Differences the operands
* Multiplication $x * $y Product of the operands
/ Division $x / $y Quotient of the operands
** Exponentiation $x ** $y $x raised to the power $y
% Modulus $x % $y Remainder of the operands
20. PHP - Arrays

An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its easy
to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which
is called array index.

 Numeric array − An array with a numeric index. Values are stored and accessed in
linear fashion.
 Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
 Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices

NOTE − Built-in array functions is given in function reference PHP Array Functions

Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function
reference.

Live Demo

<html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>
</body>
</html>

This will produce the following result −

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the
best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.

NOTE − Don't keep associative array inside double quote while printing otherwise it would
not return any value.

Example

Live Demo

<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" =>
500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>

This will produce the following result −


Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three
subjects −

This example is an associative array, you can create numeric array in the same fashion.

Live Demo

<html>
<body>

<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>
This will produce the following result −

Marks for mohammad in physics : 35


Marks for qadir in maths : 32
Marks for zara in chemistry : 39

21. PHP - Regular Expressions

Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside a another string, you can
replace one string by another string and you can split a string into many chunks.

PHP offers functions specific to two sets of regular expression functions, each corresponding
to a certain type of regular expression. You can use any of them based on your comfort.

 POSIX Regular Expressions


 PERL Style Regular Expressions

POSIX Regular Expressions


The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic
expression: various elements (operators) are combined to form more complex expressions.

The simplest regular expression is one that matches a single character, such as g, inside
strings such as g, haggle, or bag.

Lets give explanation for few concepts being used in POSIX regular expression. After that
we will introduce you with regular expression related functions.

Brackets

Brackets ([]) have a special meaning when used in the context of regular expressions. They
are used to find a range of characters.

Sr.No Expression & Description

[0-9]
1
It matches any decimal digit from 0 through 9.
[a-z]
2
It matches any character from lower-case a through lowercase z.
[A-Z]
3
It matches any character from uppercase A through uppercase Z.
[a-Z]
4
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging
from b through v.

Quantifiers

The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character having a specific connotation. The +, *,
?, {int. range}, and $ flags all follow a character sequence.

Sr.No Expression & Description

p+
1
It matches any string containing at least one p.
p*
2
It matches any string containing zero or more p's.
p?
3
It matches any string containing zero or one p's.
p{N}
4
It matches any string containing a sequence of N p's
p{2,3}
5
It matches any string containing a sequence of two or three p's.
p{2, }
6
It matches any string containing a sequence of at least two p's.
p$
7
It matches any string with p at the end of it.
^p
8
It matches any string with p at the beginning of it.

Examples

Following examples will clear your concepts about matching characters.

Sr.No Expression & Description

[^a-zA-Z]
1
It matches any string not containing any of the characters ranging from a through z and
A through Z.
p.p
2
It matches any string containing p, followed by any character, in turn followed by
another p.
^.{2}$
3
It matches any string containing exactly two characters.
<b>(.*)</b>
4
It matches any string enclosed within <b> and </b>.
p(hp)*
5
It matches any string containing a p followed by zero or more instances of the sequence
php.

Predefined Character Ranges

For your programming convenience several predefined character ranges, also known as
character classes, are available. Character classes specify an entire range of characters, for
example, the alphabet or an integer set −

Sr.No Expression & Description

[[:alpha:]]
1
It matches any string containing alphabetic characters aA through zZ.
[[:digit:]]
2
It matches any string containing numerical digits 0 through 9.
[[:alnum:]]
3
It matches any string containing alphanumeric characters aA through zZ and 0 through
9.
[[:space:]]
4
It matches any string containing a space.

PHP's Regexp POSIX Functions


PHP currently offers seven functions for searching strings using POSIX-style regular
expressions −

Sr.No Function & Description

ereg()
1
The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.
ereg_replace()
2
The ereg_replace() function searches for string specified by pattern and replaces pattern
with replacement if found.
eregi()
3
The eregi() function searches throughout a string specified by pattern for a string
specified by string. The search is not case sensitive.
eregi_replace()
4
The eregi_replace() function operates exactly like ereg_replace(), except that the search
for pattern in string is not case sensitive.
split()
5
The split() function will divide a string into various elements, the boundaries of each
element based on the occurrence of pattern in string.
spliti()
6
The spliti() function operates exactly in the same manner as its sibling split(), except
that it is not case sensitive.
sql_regcase()

7
The sql_regcase() function can be thought of as a utility function, converting each
character in the input parameter string into a bracketed expression containing two
characters.

PERL Style Regular Expressions


Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can
be used almost interchangeably with the Perl-style regular expression functions. In fact, you
can use any of the quantifiers introduced in the previous POSIX section.

Lets give explanation for few concepts being used in PERL regular expressions. After that we
will introduce you wih regular expression related functions.

Meta characters

A meta character is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.

For instance, you can search for large money sums using the '\d' meta character: /([\d]+)000/,
Here \d will search for any string of numerical character.

Following is the list of meta characters which can be used in PERL Style Regular
Expressions.

Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers

Several modifiers are available that can make your work with regexps much easier, like case
sensitivity, searching in multiple lines etc.

Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails

PHP's Regexp PERL Compatible Functions


PHP offers following functions for searching strings using Perl-compatible regular
expressions −

Sr.No Function & Description

preg_match()
1
The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
preg_match_all()
2
The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()
3
The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
preg_split()
4
The preg_split() function operates exactly like split(), except that regular expressions
are accepted as input parameters for pattern.
preg_grep()
5
The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.

22. Perl - Introduction

Perl is a general-purpose programming language originally developed for text manipulation


and now used for a wide range of tasks including system administration, web development,
network programming, GUI development, and more.
What is Perl?
 Perl is a stable, cross platform programming language.
 Though Perl is not officially an acronym but few people used it as Practical
Extraction and Report Language.
 It is used for mission critical projects in the public and private sectors.
 Perl is an Open Source software, licensed under its Artistic License, or the GNU
General Public License (GPL).
 Perl was created by Larry Wall.
 Perl 1.0 was released to usenet's alt.comp.sources in 1987.
 At the time of writing this tutorial, the latest version of perl was 5.16.2.
 Perl is listed in the Oxford English Dictionary.

PC Magazine announced Perl as the finalist for its 1998 Technical Excellence Award in the
Development Tool category.

Perl Features
 Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC,
among others.
 Perls database integration interface DBI supports third-party databases including
Oracle, Sybase, Postgres, MySQL and others.
 Perl works with HTML, XML, and other mark-up languages.
 Perl supports Unicode.
 Perl is Y2K compliant.
 Perl supports both procedural and object-oriented programming.
 Perl interfaces with external C/C++ libraries through XS or SWIG.
 Perl is extensible. There are over 20,000 third party modules available from the
Comprehensive Perl Archive Network (CPAN).
 The Perl interpreter can be embedded into other systems.

Perl and the Web


 Perl used to be the most popular web programming language due to its text
manipulation capabilities and rapid development cycle.
 Perl is widely known as "the duct-tape of the Internet".
 Perl can handle encrypted Web data, including e-commerce transactions.
 Perl can be embedded into web servers to speed up processing by as much as 2000%.
 Perl's mod_perl allows the Apache web server to embed a Perl interpreter.
 Perl's DBI package makes web-database integration easy.

Perl is Interpreted
Perl is an interpreted language, which means that your code can be run as is, without a
compilation stage that creates a non portable executable program.

Traditional compilers convert programs into machine language. When you run a Perl
program, it's first compiled into a byte code, which is then converted ( as the program runs)
into machine instructions. So it is not quite the same as shells, or Tcl, which are strictly
interpreted without an intermediate representation.
It is also not like most versions of C or C++, which are compiled directly into a machine
dependent format. It is somewhere in between, along with Python and awk and Emacs .elc
files.

23. Perl overview

Overview
Perl is a programming language used widely in the UNIX/Linux world to write everything
from quick scripts to powerful, broad-featured programs. The following is a description from
the perlintro man page:

What is Perl?

Perl is a general-purpose programming language originally developed for text manipulation


and now used for a wide range of tasks including system administration, web development,
network programming, GUI development, and more.

The language is intended to be practical (easy to use, efficient, complete) rather than beautiful
(tiny, elegant, minimal). Its major features are that it's easy to use, supports both procedural
and object-oriented (OO) programming, has powerful built-in support for text processing, and
has one of the world's most impressive collections of third-party modules.

Different definitions of Perl are given in perl, perlfaq1 and no doubt other places. From this
we can determine that Perl is different things to different people, but that lots of people think
it's at least worth writing about.

History
Perl was created in the mid-1980s by Larry Wall. Its original intent was to fill in the gap
between so-called "low-level" languages like C and C++, and the higher level scripting
languages like awk, sed, and shell scripts. It has evolved considerably since then, becoming
the de facto language of choice for many *nix system administrators and power users. It has
found broad appeal on the Internet (a mostly *nix based network) as the background code
behind many sites on the World Wide Web. A notable example is Slashdot.

Perl on DreamHost
Path to the Perl interpreter

The path to Perl on DreamHost's servers is shown below. This path is standard on *nix based
systems and most scripts should not need to be modified.

/usr/bin/perl

mod_perl is currently not supported at DreamHost. You must use FastCGI instead.

DreamHost's Perl version

View the following links for current versions of Perl.


 Ubuntu versions
 Debian Buster version

As with Python and PHP, you can build another version in your user's home directory if
necessary. However, most Perl programs should work fine with the installed version.

Installing a custom Perl version

You can also install a custom version of Perl under your username. View the following article
for instructions:

 Installing a custom version of Perl locally

Using Perl Modules

DreamHost has nearly all the common Perl modules installed, as well as many uncommon
ones.

To check whether a Perl module is installed on DreamHost's servers, log into your shell
account, and then type the following:

[server]$ perl -MThe::Module::Name -e0

where The::Module::Name is the name of the Perl module you are looking for.

The command outputs nothing when the module is found. If it's not found, an error is thrown.

Installing custom modules

You can install your own modules in your user's home directory. Follow these DreamHost
specific instructions for installing CPAN modules.

Perl FastCGI

The perl FCGI module is installed by default on DreamHost servers.

To test if FastCGI is configured and working properly, try this simple 'Hello World' program.
Paste this text into a file with the ending .fcgi. Make sure to change username to your Shell
user.

#!/usr/bin/perl

use lib qw( /home/username/lib/perl/5.8.4 );


use FCGI;
use Socket qw( :crlf ); # server agnostic line endings in $CRLF

my $counter = 0;
while ( FCGI::accept() >= 0 ) {
$counter++;

print
"Content-Type: text/plain",
$CRLF,
$CRLF,
"Hello World, in Perl FastCGI!",
$CRLF,
"I am process $$.",
$CRLF,
"I have served $counter request(s).",
$CRLF;
}

The $CRLF is a server-neutral line ending equivalent to "\015\012." It will always work. "\n"
or even "\r\n" sometimes will not.

If you change the extension of this script to .pl or .cgi so it's handled by regular CGI, you'll
notice that the PID is different on every request, and the request counter stays at 1.

Debugging
DreamHost runs suexec and requires that all cgi scripts and the directories in which they
reside not be writable by anyone but the owner (i.e., user). This means that you must change
the permissions of the script using chmod (see the following example):

[server]$ chmod -R 755 perldir

where perldir is the directory in which your perl CGI resides.

24 . Perl Variables
Variables in Perl are used to store and manipulate data throughout the program. When a
variable is created it occupies memory space. The data type of a variable helps the interpreter
to allocate memory and decide what to be stored in the reserved memory. Therefore,
variables can store integers, decimals, or strings with the assignment of different data types to
the variables.

Naming of a Variable

A variable in Perl can be named anything with the use of a specific datatype. There are some
rules to follow while naming a variable:

 Variables in Perl are case sensitive.


Example:

$John and $john are two different variables

 It starts with $, @ or % as per the datatype required, followed by zero or more letters,
underscores and digits
 Variables in Perl cannot contain white spaces or any other special character except
underscore.
Example:
 $my-name = "John"; // Invalid
 $my name = "John"; // Invalid
 $my_name = "John"; // Valid
Declaration of a Variable

Variable Declaration is done on the basis of the datatype used to define the variable. These
variables can be of three different datatypes:

 Scalar Variables: It contains a single string or numeric value. It starts with $ symbol.

Syntax: $var_name = value;

Example:

$item = "Hello"
$item_one = 2

 Array Variables: It contains a randomly ordered set of values. It starts with @


symbol.

Syntax : @var_name = (val1, val2, val3, …..);

Example:

@price_list = (70, 30, 40);


@name_list = ("Apple", "Banana", "Guava");

 Hash Variables: It contains (key, value) pair efficiently accessed per key. It starts
with % symbol.

Syntax : @var_name = (val1 = key1, val2 = key2, val3 = key3, …..);

Example:

%item_pairs = ("Apple" =>2, "Banana'=>3);


%pair_random = ("Hi" =>8, "Bye"=>9);

Modification of a Variable

Perl allows to modify its variable values anytime after the variable declaration is done. There
are various ways for the modification of a variable:

 A scalar variable can be modified simply by redefining its value.


Example:
 $name = "John";

 # This can be modified by simply
 # redeclaring the variable $name.
$name = "Rahul";
 An element of an array can be modified by passing the index of that element to the
array and defining a new value to it.
Example:
 @array = ("A", "B", "C", "D", "E");

 # If value of second variable is to
 # be modified then it can be done by
 @array[2] = "4";

 # This will change the array to,
 # @array = ("A", "B", "4", "D", "E");
 A value in a hash can be modified by using its Key.
Example:
 %Hash = ("A", 10, "B", 20, "C", 30)

 # This will modify the value
 # assigned to Key 'B'
 $Hash{"B"} = 46;

Variable Interpolation

Perl provides various methods to define a String to a variable. This can be done with the use
of single quotes, double quotes, using q-operator and double-q operator, etc.
Using single quotes and double quotes for writing strings is same but there exists a slight
difference between how they work. Strings which are written with the use of single quotes
display the content written within it exactly as it is.
Example:

$name = "John"
print 'Hi $name\nHow are you?'

The above code will print:

Hi $name\nHow are you?

Whereas strings written within double quotes replace the variables with their value and then
displays the string. It even replaces the escape sequences by their real use.

Example:

$name = "John"
print "Hi $name\nHow are you?"

The above code will print:

Hi John
How are you?

Example Code:

#!/usr/bin/perl
use Data::Dumper;
# Scalar Variable
$name = "GeeksForGeeks";

# Array Variable
@array = ("G", "E", "E", "K", "S");

# Hash Variable
%Hash = ('Welcome', 10, 'to', 20, 'Geeks', 40);

# Variable Modification
@array[2] = "F";

print "Modified Array is @array\n";

# Interpolation of a Variable

# Using Single Quote


print 'Name is $name\n';

# Using Double Quotes


print "\nName is $name";

# Printing hash contents


print Dumper(\%Hash);
Output:
Modified Array is G E F K S
Name is $name\n
Name is GeeksForGeeks$VAR1 = {
'to' => 20,
'Welcome' => 10,
'Geeks' => 40
};

You might also like