[go: up one dir, main page]

0% found this document useful (0 votes)
8 views25 pages

Mysql Part 1

The document provides a detailed guide on installing and configuring MySQL on Windows, including steps for selecting installation types and setting up a root password. It also covers troubleshooting common installation issues and basic security guidelines for running MySQL. Additionally, it introduces the MySQL privilege system and methods for adding and removing user privileges using SQL commands.

Uploaded by

zom4819
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)
8 views25 pages

Mysql Part 1

The document provides a detailed guide on installing and configuring MySQL on Windows, including steps for selecting installation types and setting up a root password. It also covers troubleshooting common installation issues and basic security guidelines for running MySQL. Additionally, it introduces the MySQL privilege system and methods for adding and removing user privileges using SQL commands.

Uploaded by

zom4819
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/ 25

U.KUMARA SWAMY MCA.

VYSHNAVIDEGREE
COLLEGE,YMG.

Unit-1
Installing and Configuring MySQL
InstalliDg MySQL on Windows
Ine MySQL installation process on Windows uses a standard Microsoft Windows Installer
(M^I) file to walk you through the installation and configuration of MySQL
Windows XP, Windows Server 2003, Windows Vista, or Windows on your
7 machine.
Go to the MySQL downloads page at
and select the Windows option from the http://dev.mysql.com/downloads/mvsql/
drop-down menu. Download theWindows MSI
5.5.html
Installer file for your systenm, either 32- or 64-bit. When this file has been
copied from the CD-ROM for this book), double-click it to downloaded (or
begin
The following'steps detail the installation of MySQL 5.5.21 on the installation process.
sequence follows the same steps regardless of your Windows Windows 7; the installation
1. Double-click the *.msi file to begin the environment.
installation sequence. You willsee the first screen of
the MySQL Setup Wizard, as shown in Figure 2.5. Click
Next to continue.

Wekome to the MySQL Server 5.5 Setup


Wirerd

ne et te Seto

Capvch )2084 11, Orade arder its atfetes,


MuSQL A

Cenc

2. After agreeing to the


terms and
Custom, or Complete (see Figure conditions,
2.6).
you are asked to choose a setup
type -Typical,
elements of MySQL to install, whereas The Custom option allows you to pick
MySQL, which range from the Complete option installs and choose
method is suitable for most documentation to benchmarking suites. all the components of
for general management users because it The Typical
includes the client, server, and in_tallation
method and click of your MySQL numerous tools
Next to continue. installation. Select Typical as the installation
MsQ Sevar 3.3 Setup
Chooco Satup Typa

Ingtek te ntconngn p
rem aures
RecoTnndd for rost eY

Rors ues oCoce t


ey be nzs, ReTme gr feaures sal be rodad tere
mended fr sonad.
Congas
Alogr fabye l be reled
Reques the rost dsk poc.

Concel

"rogramming with PHP and MySQL For


BSc V]h Sem
Page | 1
U.KUMARA SWAMY MCA.
VYSHNAVIDEGREE COLLEGE, YMG.

button to continue.
3. Confirm your choice in the next screen and click the Install
to the MySQL
4. When the installation is complete, you have the option of continuing
Instance Configuration Wizard.
Wizard, check the Launch the
To continue to the MySQL Instance Configuration the Finish button.
MySQL Instance Configuration Wizard check box and click

Complett the MyysQA Server 5.5 Setup


Wizord

Orrte Frt bon the Seto htord,

MySQL
Arehas

the Next
Wizard Welcome screen, click
Configuration
MySQL Instance configuration:
5. When you see the in the wizard. You will see two options for server click Next to
button to go to the next step Detailed Configuration
radio button, and then
Standard. Select the
Detailed and
Machine, or
continue. running: Developer Machine, Server
machine you are
YouSelect the type of Machine.
Dedicated MySQL Server continue.
making your selection, click Next to
After sQLSavsrstanco
Conguraaon Wizard

Conguato
MyssA Server nstance
CoaioUe the kMSOL Serer
i5 sere intane
dk nd GRU esge
riuence mono,
Flease sded s sever
tpe. TNg

a deopnert N and youe onttwi


sf
shoutd eny usA a a i z
nen & MSQ San

Cnyer N h e
agciatDns m u t e r u n n n g on
Seta server Wetpprebon senok
Chhoose this pgton tor

CDoaldSOL S v e Hachne SOL Detabse Serer.


MSQL
Ths nehene o dedcsted to run the
see Abe n, MQ2
Se web or neu
other seNers RCH

Ca

base
mnemory space to install data
need to select the
6. In this step we

Page | 2
For BSc VÊh Sem
Programming with PHP and MySQL
VYSHNAVI DEGREE COLLEGE, YMG.
U.KUMARA SWAMY MCA.

Mys enver staeContgaton


Conoue fhe AE Serurr SS sver n starce

to u:e te dett
Pltsse select he eNetor hetrnoDS drtatie f rou se rt wrt
settngs.
mo00 tstepce Settng

Laslepta bouid be picad.

Fle Sptert NIES

CSnc

7. After then we need to set a password for our data base it is called as Root password.
MysQL sever istance Contiguration Wizard

Mys Sne stance Contguraton


Conioure 1he MsOL Server 5.5 serve hstance

Piese sttne seatty cpiors


g Nodiry Secuty Sottiegs
New roct passar: eter the root password.

Confi Retype the passroId

rEnable toot access from rtmote mschines

r reate An AnaoaLE Rcourt


hs opton uill reate an enonmous acsurrt pn thts serrs.
Flesse note thet thts can lesd to en ieue yslen.

Cance

8. When we press the net button, all the configurations can be done. Those configurations can
be displayed as given bellow:
MysqL Sevar rstaco Contigurason Wizard

ysQ Sener rstace Conhgtor


Conigure the MSOL Serier $5 serve in stance

Processing conhgursten

Prpare cottgustian

B sturt senice

S Apply secunity setings


Coaßguton eoaled
mados Sevi MysQL nstlled

Ongs ppled.
Pres (Fnish] to cdose te Wzrd.

Troubleshooting Your Installation


If you have any problems during the installation of MySQL, the first place you should look is
Appendix A, "Problems and Common Errors," in the MySQL Manual, which is located at
http:// dev.mysql.com/doc/refman/5.5/en,/problems.html.
The following are just a few of the common installation problems:

Programming with PHP and MySQL For BSc VIh Sem Page | 3
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE, YMG.
On Linux/ UNIX and Mac OS X, incorrect permissions do not allow you to start the MySQL
daemon. If this is the case, be sure that you have changed owners and groups to match those
indicated in the installation instructions.
If you see the message ACcess denied when connecting to MySQL, be sure that you are
using the correct username and password.
. If you see the message Can't connect to server, make sure that the MySQL daemon is
running.
BasicSecurity Guidelines
Regardless of whether you are running MySQL on Windows, Linux/UNIX, or Mac OSX, and
no matter whether you administer your own server or use a system provided to you by your
Internet service provider, you must understand basic security guidelines.
Starting MySQL
Securing MySQL begins with the server startup procedure. If you are not the administrator
report
of the server, you cannot change this, but you can certainly check it out and
vulnerabilities to your Internet service provider.
If you see that MySQL is running as root on your system, immediately contact your Internet
the
service provider and complain. If you are the server administrator, you should start
the startup
MySQL process as a non-root user or specify the preferred username in
Commnand line:
# mysqld -user=no_root_user_name
command:
For example, if you want to run MySQL as user mysql, use this
# mysqld -user=mysql
through the mysqld_safe
However, the recommended method for starting MySQL is
installation:
startup script in the bin directory of your MySQL
# bin/nysqld_safe -user=mysql

Introducing the MySQL Privilege Systemconnect, and for each


on. The first time you try to
The MySQL privilege system is always things:
subsequent action, MySQL checks the following three
Where you are accessing from (your host)
password)
Who yOu say you are (your username and
command privileges)
What you're allowed to do (your
database called mysql, which is automatically created
All this information is stored in the privilege-related tables in the mysql database,
when MySQL is installed. There are several
such as the following:
columns_priv-Defines user privileges for
specific fields within a table
db Defines the pernissions for all databases
on the server
host-Defines the acceptable hosts that can
connect to a specific database
procs_priv Defines user privileges for
stored routines
for specific tables within a database
> tables_priv- Defines user privileges for a specific user
user- Defines the command privileges
this chapter as you add a
These tables will become more important to you later in tables exist and must have
remember that these
few users to MySQL. For now, just
relevant data in them for users to coplete actions.
Understanding the Two-Step Authentication
Process
process.
As you've learned, MySQL checks three things during the authentication
steps:
The actions associated with these three things are performed in two

Programming with PHP and MySQL For BSC VÊh Sem Page | 4
YMG.
VYSHNAVIDEGREE COLLEGE,
U.KUMARA SWAMY MCA.
password pair
looks at the host you are connecting from and the username and
. 1MySQL for your
you are using. If your host is allowed
to connect, your password is correct second
host, MySQL moves to the
usernamne, and the username matches
one assigned to the
step. attempting to use, MySQL verifies that
your user
2. For whichever SQL command you are that database, table, and field.
has permissions to perform that action for

Adding Users to MySQL to


users is the GRANT command. By connecting
The simplest method for adding newone other method
command to set upa new user. The
MySQL as the root user, you can issue which
relevant tables in the mysql database,
is to issue INSERT statements into all the
used to store permissions.
requires you to know all the fields in the tables than the simple GRANT command.
complicated
This method works just as well but is more shown here:
The simple syntax of the GRANT command is
GRANT privileges
ON databasename. tablename
TO username@host
IDENTIFIED BY "password";
Following are some of the common privileges you can grant.
> ALL-Gives the user all common privileges.
indexes.
> ALTERUser can alter (modify) tables, columns, and
> CREATE-User can create databases and tables.
> DELETE-User can delete records from tables.
DROPUser can drop (delete) tables and databases.
FILEUser can read and write files; this privilege is used to import or dump data.
INDEX-User can add or delete indexes.
INSERT-User can add records to tables.
PROCESSUser can view and stop system processes; only trusted users should be
able to do this.
RELOAD-User can issue FLUSH statements; only trusted users should be able to do
this.
SELECT-User can select records from tables.
SHUTDOWNUser can shut down the MySOL server; only trusted users should be
able to do this.
UPDATE-User can update (modify) records in tables.
Removing User Privileges
Removing privileges is as simple as adding them; instead of the GRANT Command, you use
REVOKE. The REVOKE command syntax is as follows:
REVOKE privileges
ON databasename.tablenane
FROM username@hostname;

Current and Future Versions of Apache


The Apache HTTPD server website at http://httpd.apache.org shows announcements for
releases of the Apache 2.0.x, Apache 2.2.x, and Apache 2.4.x versions. As you can understand
by the version numbers, Apache 2.0.x is the oldest of the three versions. The Apache
Software Foundation maintains all three versions, but the features in Apache 2.4.x include

Programming with PHP and MySQL For BSc VIh Sem Page | 5
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE, YMG.

the latest and greatest; it is the version used in this chapter. Howeve, if you choose to install
(or already have installed either in a local or external development environment)
Apache 2.2.x or even Apache 2.0.x, all the PHP and MySQL code in this book will still work
as described. In fact, you will find a number of hosting providers still using Apache 2.0.X
issues
not even Apache 2.2.x, let alone the newest Apache 2.4.x branch. If you experience ny
example,
with installing Apache 2.4.x as described in thischapter, try an earlier version (for
Apache 2.2.x); the installation instructions are renmarkably similar.
for updates containing
The Apache Software Foundation uses minor and revision numbers
nor revision releases follow a set release
ecurity enhancements or bug fixes. Neither minor
to the code and
schedule. When enhancements or fixes are added
releases a new version.
thoroughly tested, the Apache Software Foundation

Choosing the Appropriate Installation Method


getting a basic Apache installation in place.
You have several options when it comes tocan have access to the full source code of the
Apache is open source, meaning that
you Source:
you to build your own custom server. Building from
software, which in turn enables to build
greatest flexibility because it enables you with thirdparty
Building from source gives you the extend the server
modules you do not need, and
acustom server, remove upgrade to the latest
source code enables you to easily
modules. Building Apache from versions from vendors can
quickly apply security patches, whereas updated
versions and
take days or weeks to appear. download them
Installing a Binary: available from vendors or you can
installations are installations provide a
convenient
Linux/UNIX binary
Foundation website. Binary knowledge or with no
Software
from the Apache imited system administration
for users with prepackaged Apache
way to install Apache Third-party commercial vendors provide
support, and so on. The
special configuration needs.an application server, additional modules,
platform where
installations together with installer for Windows systems-a
Foundation provides an
Apache Software Linux/UNIX systems.
commnonly available than in
a compiler is less
Linux/UNIX
Installing Apache on Apache 2.4.1 on
Linux/UNIX. The
fresh build of
how to install a source are as follows:
This section explains successfully install Apache from
general steps necessary
to
software.
1. Download the
script.
2. Run the configuration install it.
code and
3. Compile the steps in detail.
sections describe these
The following Code download.cgi. You
Downloading the Apache Source located at http://httpd.apache.org/

compression
Apache download site is packaged with different
The official Apache source code, compressed with
several versions of the the tar utility and then
can find packed with
distribution files are first
methods. The system. This
compress utility. installed on your
either the gzip tool or the gunzip utility FreeBSD and
the *. tar.gz version if you have the operating systems such as
Download open source included in
comes installed by default in
not present in your system. (It isn't
*.tar.Z file if gunzip is
utility
Linux. Download the commercial UNIX operating
systems.)
installation of many
the default

Page | 6
For BSc VIh Sem
Programming with PHP and MySQL
VYSHNAVI DEGREE COLLEGE, YMG.
U.KUMARA SWAMY MCA.
VERSION.tar.gz,
Tne ile you want to download will be named something similar to httpd-
where VERSION is the most recent release of Apache. For example,
Apache version 2.4.1 is distributed as a file named httpd-2.4.1.tar.gz. Keep
the downloaded
local/src/.
ile in a directory reserved for source files, such as /usr/src/ or /usr/
Uncompressing the Source Code
suffix), you can
lf you downloaded the tarball compressed with gzip (it will have a tar.gz
uncompress it using the gunzip utility (part of the gzip distribution).
You can uncompress and unpack the software by typing the following command:
#gunzip <httpd-2.4".tar.gz | tar xvf -
Uncompressing the tarball creates a structure of directories, with the top-level directory
named httpd-VERSION. Change your current directory to this top-level directory to prepare
for configuring the software.
Preparing to Build Apache
the configure script in
You can specify which features the resulting binary will have by usingwith
the top-level distribution directory. By default, Apache is compiled a set of standard
modules compiled statically and is installed in the /usr/local/apache2 directory. If you are
happy with these settings, you can issue the following command to configure Apache:
# fconfigure
Building and Installing Apache
The make utility reads the information stored in the makefiles and builds the server and
modules. Type make at the command line to build Apache. You will see several messages
indicating the progress of the compilation, and you will end up back at the prompt. After
compilation is finished, you can instal Apache by typing make install at the prompt. The
makefiles install files and directories and return you to the prompt:
Installing header files
Installing build system files
Installing man pages and online manual

make[1]: eaving directory '/usr/local/ bin/httpd-2.4.1


#
The Apache distribution files should now be in the/usr/local/apache2 directory,
as specified by the-prefix switch in the configure command. To test that the
httpd binary built correctly,type the following at the prompt:
#/ust/local/apache2/bin/httpd -v
You should see the following output (your version and build date will be different):
Server version: Apache/2.4.1 (Unix)
Server built: March 12 2012 11:47:22
Unless you want to learn how to install Apache on Mac OS Xor Windows, skip ahead to the
"Apache Configuration File Structure" section to learn about the Apache configuration file.
Installing Apache on Mac OS X
Lucky you, Apache is already installed on Mac OS X! By default, the Apache server
binary is located at /usr/sbin/httpd. Configuration files such as httpd.conf, the master
configuration file for Apache, are in /etc/httpd. Because Apache is ready to go and fully

Programming with PHP and MySQL For BSc VIth Sem


Page | 7
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE, YMG.

prepared to use PHP, skip ahead to the "Apache Configuration File Structure" section to
learn more about the Apache configuration file and how to use it.

Installing Apache on Windows


Apache 2.2 runs on most Windows platforms and offers increased performance and stability
over earlier versions for Windows. You can build Apache from source, but because not many
Windows users have compilers, this section deals with the MSI installer version.
Before installing Apache, make sure that you are not currently running a web server (or
instance, aprevious version of Apache or Microsoft Internet Information Services) on yor
machine. You might want to uninstall or otherwise disable existing servers. You can run
several web servers, but they must run in different address and port combinations.
and look for a
Before downloading the installer, take a moment-a very important moment-
statement on the downloads page (found at http://httpd.apache.org/ download.cgi) that
says "If you are downloading the Win32 distribution, please read these important notes."
The direct URL to these notes is http://www.apache.org/dist/
httpd/binaries/win32/README.html.
The Apache Software Foundation mnaintains this page for the benefit of Windows users who
want to run a version of the Apache server. On this page, there are notes for nearly every
flavor of Windows still in use, and it is in your best interest to read the information
presented. Iguarantee that if you are running Apache as either a production or development
server, you will find relevant information on the notes page.

When you're ready to begin the installation, look for the link labeled Win32 Binary including
OpenSSL(MSI Installer). After you download the
installer, double-click the file to start the
installation process. You willget a welcome screen, as shown in Figure

Apache HITP Server 2.2 - Installation Wizard

Wekoome to the Installation


Wizard for
Apache HIIP Server 2.2.22

The lnstalajon Vtzard wil nstall Apache HTTP Server 22.22


Next.
on your compute,To ontinue, didk

copyright aw and
WARNING: Ths program Is protected by
Internabona treaties.

Next> Cancel
<Back

and you will be promnpted to accept the


Click Next to continue the installation process,
you can do whatever you want with the
Apache license. Basically, the icense says that

Page | 8
Programming with PHP and MySQL For BSc VÊth Sem
U.KUMARA SWAMY MCA. VYSHNAVIDEGREE COLLEGE, YMG.

Sottware -including making proprietary modifications except claim that you wrote it, but
De sure to read the license so that you fully understand the terms. After you accept the
license, the installer presents you with a brief introduction to Apache. Following that, it asks
you to provide basic information about your computer, as shown in Figure 3.2. This includes
the full network address for the server (for instance, mycomputer.mydomain.com) and the
administrator's emailaddress.
The server name is the name your clients will use to access your server, and the
administrator email address is added toerror messages so that visitors know how to contact
you when something goes wrong.
Apache HTTP Server 2.2 -Installation Wizard
Server Infomation
Please enter your server's infomation.

Network Domain (e.g. somenet.com)

Server Name (c.g, ww.sonenet.com:

Administrator's Email Address (e.g. webmaster @somenet.com):

Instal Apache HITP Server 2.2progams and shortauts for:


for Al Users, on Port 80, as a Service --Recomnended.
C only for the Qurent User,, on Port 8080, when started Manualy.
InstllShield

<Badk Next > Cancel

Also on this screen, you are prompted to select which installation shortcuts should
be installed- those for starting Apache as a service or those for starting Apache
Installing Apache as a service causes it to run every time Windows starts, andmanually.
control it through the standard Windows service administration tools. Installing you can
Apache
the current user requires you to start Apache manually and set the default port on for
Apache listens to requests to 8080 (instead of 80). Select the appropriate radio which
click Next to continue. button and
The next screen enables you to choose the type of installation:
installation means that Apache binaries and documentation aretypical or custom. A typical
installed, but headers and
libraries are not. This is the best option to choose unless you
modules. plan to compile your own
A custom installation enables you to choose whether to
install header files or documentation.
After selecting thetarget installation directory, which defaults to
c:\Program Files (x86)\ Apache Software Foundation\
with the installation process. If everything goes well, Apache 2.2, the program proceeds
it presents you with the final screen,
shown in Figure

Programming with PHP and MySQL For BSc V[th Sem


Page 9
U.KUMARA SWAMY MCA. VYSHNAVIDEGREE COLLEGE, YMG.

ERVER
PRJJEGT
t
Apache HTTP Server 2.2 - Installation Wizard

Installation Wizard Completed

The instalaton WIzard has successfully installed Apache HTTP


Server2.2.22. Odk Fnsh to ent he vizard.

Fnish Cancel
< Eac

Configuration File
Structure
httpd.conf. This
Apache
in text files. The main file is installation.
configuration information customize yOur
Apache
Apache keeps all its containers that enable you to performance, and
directives and as authorization,
file contains Apache, such settings refer. For
specific settings of to which those
Directives configure the context directory, or to a
Containers specify server as a whole, toa
network
parameters.
configuration can
refer to the
authorization
example,
single file.
Directives directive syntax:
apply for Apache
The following rules arguments follow the directive
name.
directive spaces. have no
The separated by directive; some
arguments are directive to
The directive arguments vary
from
type of ending
The number
and different line by
it on a
continue
arguments.
single line, but you can
directive occupies
a character (\). its own line.
A backslash must appear on at
line with a directive, and for directives
the previous precede the reference

The pound sign (#) should offers You'll soon learn about somne
a quick
>
http://httpd.apache.org/docs/2.4/mod/quickreference.
documentation
html. the online
The
Apache server knowledge using
supplement your
you should
directives, but
of the basic
documentation.
this model:
typically follows
documentation for directives description of the directive.
Compulsory
parameters
The Apache provides a brief directive options.
Description- This entry format of the brackets.
entry explains the in italics and
This appear
. Syntax italicS, parameters
and optional default value, it appears
here.
the directive can
appear.
appear in has a sections in
which host,
Default Ifthe directive containers or server config, virtual
the are
entry details possible values
C o n t e x t - This containers. The

next section explains


The
irectory, a n d .htaccess. Page | 10

Sem
MysQL For BSc VÊh
o g r a m m i n g with
PHP and
VYSHNAVIDEGREE COLLEGE, YMG.
U.KUMARA SWAMY MCA.

.Override-Apache directives belong to different categories. The Override field specifies


which directive categories can appear in .htaccess per-directory configura ion fles.
Status-This entry indicates whether the directive is built in Apache (core), belongs to
one
of the bundled modules (base or extension, depending on whether they are compiled by
but not
default), is part of a multiprocessing module (MPM), or is bundled with Apache
ready for use in a production server (experimental).
Module- This entry indicates the module to which the directive belongs.
Compatibility-This entry contains information about which versions of Apache support
the directive.
Further explanation of the directive follows these entries in the documentation, and a
reference to related directives or documentation might appear at the end.

Troubleshooting
The following subsections describe several common problems that you might encounter the
first time you start Apache.
Already an Existing Web Server
Ifa server is already running on the machine and is listening to the same IP address
and port combination, Apache cannot start successfully. You will get an entry in the
error log file indicating that Apache cannot bind to the port:
[crit] (48)Address already in use: make_sock: could not bind... [alert) no listening sockets
available, shutting down
To solve this problem, you need to stop the running server or change the Apache
configuration to listen on a different port.
No Permission to Bind to Port
You will get an error if you do not have administrator permissions and you try to
bind to a privileged port (between 0 and 1024):
[crit] (13)Permission denied: make_sock: could not bind to address 10.0.0.2:80 [alert] no
listening sockets available, shutting down
To solve this problem, you must either log on as the administrator before starting Apache or
change the port number; 8080 is acommonly used nonprivileged port.
Access Denied
You might not be able to start Apache if you do not have permission to read the
configuration files or to write to the log files. You willget an error similar to the following:
(13) Pernuission denied: httpd: could not open error log file
This problem can arise if the user who built and installed Apache is different from
the user trying to run it.
Installing PHP on Windows
Installing PHP on Windows requires nothing more than downloading the distribution file.
To download the PHP distribution files, go to the homne of PHP on Windows,
http://windows.php.net/, and follow the link to the Downloads page. Grab the latest
version of the thread-safe ZIP package-for this example, we are using 54.0. Our
distribution will be named something similar to php- VERSION.zip, where VERSION is the
most recent release number.
After the file downloads to your system, double-click it to launch our unzipping software.
The distribution is packed up with relative pathnames already in place, so extract the files to
a new directory called C:\ php\, where it will place all the files and subdirectories under that
new directory.

Programming with PHP and MySQL For BSc VIth Sem Page | 11
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE, YMG.

Next, go to the C:\php\ directory and copy the php.ini-development file to php.ini. Now, to
get a basic version of PHP working with Apache, we need to make a few minor
modifications to the Apache configuration file.
Integrating PHP with Apache on Windows
To ensure that PHP and Apache get along with one another, we need to add a few items to
the httpd.conf configuration file. First, find a section that looks like this:
# Example:
# LoadModule foo_module modules/mod_foo.so

LoadModule access_module modules/mod_access.so


#LoadModule vhost_alias_nmodule modules/mod_vhost_alias.so
At the end of this section, add the following:
LoadModule php5_module C:/ php/php5apache2_2.dll
In addition, add the following to ensure Apache knows where php.ini resides:
PHPIniDir "C:/php/" Next, look for this section:

# AddType allows you to add to or override the MIME configuration


# file mime.types for specific file types.
Add the following line:
AddType application/x-httpd-php -php
parse files that end with the .php extension.
This statemernt ensures that the PHP engine will
you might want to parse all *.html files
Our selection of filenames might differ;for example,
as PHP files. warning;
Apache. The server should start without
Save the httpd.conf file and then restart
PHP is now part of the Apache web server.
The php.ini. Basics
the php.ini
compiled or installed PHP, you can still change its behavior with
After we have
file. /usr/ local/php/lib or the lib
Linux/UNIX systems, the default location for this file is
On configuration time.
installation location we used at directory as
subdirectory of the PHP PHP directory or another
this file should be in the
On a Windows system, httpd.conf file.
PHPIniDir in the Apache the
specified by the value of forms: values and flags. Value directives take
file come in two
Directives in the php.ini sign.
value separated by an equal take the form of a directive
form of adirective name anda directive. Flag directives
directive to include 1,
Possible values vary from separated by an equal sign. Positive terms
negative termn ignored.
name and a positive or 0, Of, No, and False. Whitespace is
terms include to restart the
On, Yes, and True. Negative settings at any time, but after you do, you need php.ini file
php.ini the
We carn change your At some point, take time to read through
take effect.
server for the changes to configure.
you° ownto see the types of things that you can
on

Page | 12
For BSc VIh Sem
Programming with PHP and MysQL
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE, YMC.

Basics of PHP scripts


Open any text editor. (Notepad, wordpad).
Type the following php program.
<?php
echo "Hello Web!";
?>
save the file in root directory as aprgl.php (root directory -
c:\ xampp\htdocs\ directory)
Execute the php program by using browsers like Mozilla fire fox/ google chrome/
internet explorer.(type at the address bar in browser - localhost/ directory/prgl.php
and press entery key)
>the output will be displayed in browser's document area.
Beginning and Ending aBlock of PHP Statements:

Table 4.1 PHP Start and End Tags


Tag Style Start Tag End Tag
Standard tags <?php ?>

Short tags <?

ASP tags <%

Script tags <script language="php"> </script>

The echo and print) Statements :- These two statements are used to print the
information on the browser.
Example :- echo "example";
print("example");
Combining HTML and PHP:
Listing 4.2 A PHP Script Incorporated into HTML
1: <\DOCTYPE html>
2: <html>
3: <head>
4: <title>A PHP script including HTML</title>
5: </head>
6: <body>
7: <h1><?php echo "hello world";
8: </body> ?></h1>
9: </html>

Adding Comments to PHP Code:


A conment is text in a script that is ignored by
the PHP engine. Comments can make code
more readable or annotate a script.
Bingle-line comments begin with two forward slashes (//) -
or a single hash or pound sign (#). The PHP engine the preferred style -
ignores all text between these
Programming with PHP and MySQL For BScV[h Sem
Page 13
U.KUMARA SWAMY MCA. vYSHNAVI DEGREE COLLEGE, YMG
marks and either the end of the line or the PHP close tag:
/this is acomment
# this is another comment
Multiline comments begin with a forward slash followed by an asterisk (/*) and
end with an asterisk followed by a forward slash (*/):
/*
this is a comment
none of this will
be parsed by the
PHP engine
*/
Features of PHP
Iutroduction
PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-used open source
server-side scripting language to write dynamically generated web pages. PHP scripts are
executed on the server and the result is sent to the browser as plain HTML.
PHP carn be integrated with the number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. PHP can be embedded
within a normalHTML web pages. That means inside
your HTML documents you'llhave PHP statements like this:
What is PHP.
> PHP is an acronym for "PHP: Hypertext Preprocessor"
> PHP is a widely-used, open source scripting language
> PHP scripts are executed on the server
> PHP is free to download and use
What is a PHP File?
> PHP Gles can contain text, HTML, CSS, JavaScript, and PHP code
> PHP code are executed on the server, and the result is returned to the browser as
> plain HTML
> PHP files have extension".php"
What Can PHP Do?
> PHP can generate dynamic page content
> PHP can create, open, read, write, delete, and close files on the server
> PHP can collect form data
> PHP can send and receive cookies
> PHP can add, delete, modify data in your database
> PHP can be used to control user-access
> PHP can encrypt data
Why PHP?
X, etc.)
> PHP runs on various platforms (Windows, Linux, Unix, Mac OS
etc.)
> PHP is compatible with almost all servers used today (Apache, IIS,
> PHP supports a wide range of databases www.php.net
PHP is free. Download it from the official PHP resource:
} PHP is easy to learn and runs efficiently on the server side
Advantages of PHP
PHP developers,
OOpen source: It is developed and maintained by a large group of

Page | 14 P
Programming with PHP and MySQL For BSc V[h Sem
VYSHNAVI DEGREE COLLEGE,
YMG.
U.KUMARASWAMY MCA.
abundant extension library.
hs will helps in creating a support community,
Speed: It is relative fast since it uses much system resource. with C, it's very
O
for those who are familiar
U Easy to use: It uses C like syntax, so
website scripts.
easy for them to pick up and it is very easy to create
so when bugs are found, it can
OStable: Since it is maintained by many developers,
be quickly fixed.
find functional modules you need such
UPowerful library support: we can easily
as PDE, Graph etc. connect to database easily using
DBuilt-in database connection modules: You can
we will use database
PHP, since many websites are data/content driven, so
apps.
frequently, this will largely reduce the development time of web Mac, it's easy for
Windows, Linux and
OCan be run on many platforms, including
users to find hosting service providers.
Disadvantages of PHP
can see the source code, if there are
OSecurity :Since it is open sourced, so all people explore the weakness of PHP.
bugs in the source code, it can be used by people to
since it is not very modular.
ONot suitable for large applications: Hard to maintain programmers and lead to
OWeak type: Implicit conversion may surprise unwary compare equal because
unexpected bugs. For example, the strings "1000" and "le3"
they are implicitly cast to floating point numbers.
Building blocks of PHP
Explain about Variables?
Definition
Avariable is a special container that we can define, which then "holds" a value,
such as a number, string,object, array, or a Boolean.
PHP Variables
A
variable can have a short name (likex and y) or a more descriptive name (age,
carname, total volume).
Rules for PHP variables:
> Avariable starts with the $ sign, followed by the name of the variable
> A variable name must start with a letter or the underscore character
> A variable name cannot start with a number
Avariable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and_)
> Variable names are case-sensitive ($age and $AGE are two different variables)
Examples
<?php
$txt = "W3Schools.com";
echo "I love $txt!";

<?php
Bx =5;
By = 4;
echo $x +Sy:

rogramming with PHP and MySQL For BSc VIh Sem


Page | 15
VYSHNAVI DEGREE COLLEGE, YMG.
U.KUMARA SWAMY MCA.

PHP Variables Scope


is the part
In PHP, variables can be declared anywhere in the script. The scope of avariable
of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local
global
static

Global and Local Scope


a GLOBAL SCOPE and can only be accessed
A variable declared outside a function has
outside a function:
Example
<?php
$x = 5; // global scope
function myTest() {
generate an error
I/ using x inside this function will
$x</p>";
echo "<p>Variable x inside function is:

myTest): $x</p>";
echo "<p>Variable x outside function is:
within
?>
function has a LOCAL SCOPE and can only be accessed
a
A variable declared within
that function:
Example
<?php
function myTest() {
$x =5; // local scope
function is:$x</p>";
echo "<p>Variable x inside

myTest();
//using x outside the
function will generate an error
function is: $x</p>";
echo "<p>Variable x outside
?> variables
Super global Variables PHP has several predefined
your own creation, all
addition to global variables of present, and their values are available to
In always
These variables are actually an array of other
variables:
called superglobals. following superglobals is method.
our scripts. Each of thevariables provided toa script through the POST method.
GET
$_GET contains any variables provided to a script through the
$_POST contains any through a cookie.
variables provided to a script
$_COOKIE contains any provided to script through file uploads.
a
$_FILES contains any
variables script locations.
information such as headers, file paths, and
.$_SERVER COntains
the server
variables provided to a script as part of
.$_ENV containsany
POST, or
environment.
provided to a script via GET,
.$_REQUEST containsany variables
COOKIE
input mechanisms.
Page 16

For BSc VÊh Sem


PHP and MySQL
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE, YMG.

S_SESSIONcontains any variables that are currently registered ina session.


Global Scope variable
and can only be accessed
A variable declared outside a function has aGLOBAL SCOPE
variable from within a
outside afunction. The global kevword is used to access a global
function.
Example
<?php
Sx =5;
$y = 10;
function myTest) {
global $x, $y:
$y =$x +$y;
myTest():
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS [index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.
Example
<?php
$x=5;
$y = 10;
function myTest()
$GLOBALS[y'] =$GLOBALS['*]+ $GLOBALS['y'];
myTest);
echo $y: l/ outputs 15

Static
Normally, when a function is completed/executed, all of its variables are
sometimes we want a local variable NOT to be deleted. We need deleted. However,
To do this, use the static keyword whern you first declare it for a further job.
Example the variable:
<?php
function myTest() {
static $x=0;
echo $x;
$xt+;

myTest):
myTest):
myTest);
?>

Programming with PHP and MySQL For BSc V[h Sem


Page | 17
U.KUMARA SWAMY MCA. VYSHNAVIDEGREE COLLEGE, YMC

Data Types
Different types of data take up different amounts of menmory and may be treated differently
when they are manipulated by a script.
PHP is loosely typed, meaning that it automatically determines the data type at the time data
is assigned to each variable.
Variables can be used flexibly - in one instance, a variable can hold a string and then later in
the script it can hold an integer or some other data type.
PHP supports the following data types:
Type Example Description
Boolean true One of the special values true or false
Integer 5 A whole number
Float or double 3.234 Afloatingpoint number
String "hello" A collection of characters

Object An instance of a class

Array An ordered set of keys and values


Resource Reference to a third-party resource (a
database, for example)
NULL An uninitialized variable

Examples
(string)
<?php
$x= "Hello world!";
$y = Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
(null) <?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
integer
<?php
Bx = 5985;
ar _dump($x);
oat
?php
K=10.365;
r_dump($x);

ay
ohp Page | 18 P.
MySQL For BSc VÊH
Sem
ramming with PHP
and
YMG
VYSHNAVIDEGREE COLLEGE,
U.KUMARA SWAMY MCA.

Scars =
array("Volvo" "BMW",Toyo
ta");
var_dump(Scars);
2>

Changing Type with settype):


settype() is used to change the type of a variable.
Syntax:
settype(Svariabletochange, 'new type');
<?php
$varl98';
$var2='01;
settype($var1, "integer");
settype($var2, "integer");
echo ($varl.'<br>');
echo ($var2.'<br>);
echo ($var1+$var2.'<br>');
?>
Changing Type by Casting
Casting produces a copy, leaving the original variable untouched. To change type through
casting, we indicate the name of a data type, in parentheses, in front of the variable you are
copying.
$newvar = (integer) $originalvar
Example
<?php
/*** create an int ***/
Snum = 6;
/*** dump the type ***/
var dump($num);
echo '<br />;
/*** cast to string ***/
$num - (string) $num;
/*** dump again **/
var_dump(Snum);
?>

Operators and Expressions


An operator is a symbol or series of symbols that, when
performs an action, and usually produces a new value. used in conjunction with values,
An operand is a value used in conjunction with an operator.
operands to one operator. There are usually two or more
PHP divides the operators in the
o Arithmetic operators
following groups:
Assignmernt operators
Comparison operators
o Increment/ Decrement operators
o Logical operators

rogramming with PHP and MySQL For BSc VIth Sem


Page | 19
VYSHNAVI DEGREE COLLEGE,
U.KUMARA SWAMY MCA.

String operators
o Array operators
Arithmetic operatorS perform commonarithmetical
with numeric values to
The PHP arithmetic operators are used multiplication etc.
subtraction,
operations, such as addition,
Arithmetic operators: Sample Result
Example
Name
Operator 13
10+3
+
Addition
7
10-3
Subtraction 3.3333333333333

10/3
Division 30
10*3
Multiplication
1
10%3
Modulus

values to write a value to


Assignment operators used with numeric
operators are
The PHP
assignment gets
means that the left operand
avariable. operator in PHP
is "=". 1t
assignment
expression on the
right.
The basic assignment
of the
set to the value
new
and return the
$x = 4; to add
equals a8s s i g n m e n t operator (+=)
4;//$x now
$x = $x + combination

a
use Operators

we can also Assignment Equivalent To


Combined
value.
Some $X +
5
TABLE 5.3 $X =
Example
$X - 5
$X + 5 $X =
Operator
$X /
5
.= 5 $X =
$X 5
$X * =
$X
$X /= 5 5
$X %
$X =
$X *= 5 test"

SX. "
$X =
$X %= 5
test "
$X .= return
operands
and
their
using fails.
tests the test
if
orfalse
c o m p a r a t i v e

Comparison operators
perform s u c c e s s f u l

is
the test
operators

C o m p a r i s o n

value
true if
Boolean

the
YMG.
VYSHNAVIDEGREE COLLEGE,
U.KUMARA SWAMY MCA.

TABLE 5.4 Comparison Operators Result


Example (Sx Is 4)
Returns True If...
Operator Name false
$X == 5
Left is
Equivalence
equivalent to
right. true
$x != 5
Left is not
Nonequivalence
equivalent to
right.
Result
Returns True lf... Example (Sx Is 4)
Operator Name true
$> 4
Left is equivalent
ldentical
to right, and they
are the same type. false
"A "
$X ==:
Left is equivalent
Nonequivalence
to right, but they
same
are not the

type. false
$X > 4
Left is greater
Greater than
than right.
$x >= 4 true
Greater than or Left is greater
than or equal
equal to
to right. false
$x < 4
Left is less
Less than
than right. true
$X <= 4
Less than or Left is less than

equal to or equal to right.

integer variable,
Increment/Decrement operators integer constant 1 from an
add or subtract the
These operators allow us to
variable itself.
assigning the result to the decrenment or pre
increment/ decrement.
post increment /
These are applied as
below table.
These are shown in

Description
Operator
Name
returns $x
Increments $x by one, then
Pre-increment
++$X increments $x by one
Returns $x, then
Post-increment

$X++ returns $x
Decrenents $x by one, then
Pre-decrement

--$x decrements $x by one


Returns $x, then
Post-decrement

$X-
Page | 21

Sem
MySOL For BSc VÊh
VYSHNAVI DEGREE COLLEGE
U.KUMARA SWAMY MCA.

Logical operators
Logicaloperators test combinations of Boolean values.

Returns True If... Result


Operator Name Example
O Left or right is true. true | | false true

or Left or right is true. true or false true

Xor Xor Left or right is true, true Xor trUe false


but not both.
&& And Left and right are true. true && false false

and And Left and right are true. true and false false
Not The single operand is ! true false
not true.

String operators
PHP has two operators that are specially designed for strings.
Name Example Result
Operator
Concatenation of $txt1
Concatenation $txti. $txt2
and $txt2

Appends $bxt2 to $txt1


Concatenation $txti .= $txt2
assignment

Array operators
The PHP array operators are used to compare arrays.

Operator Name Example Result

Union $x + $y Union of $x and $y


Returns true if $x and $y have
the same
Equality $x == $y
key/value pairs
have the same
$x === $y Returns true if $x and $y
Identity order and of
key/value pairs in the same
the same types
$y
$x != $y Returns true if $x is not equal to
Inequality
$x <> $y
Returns true if $x is not equal to $y
Inequality
Returns true if $x is not identical to $y
Non-iderntity $x !== $y

Operator Precedence
The PHP engine usually reads your expression from left to right. However, you can override
operator precedence by putting parentheses around your expressions.

Progranming with PHP and MySQL For BSc VIh Sem Page | 22 P.
VYSHNAVI DEGREE COLLEGE,
YMG.
U.KUMARA SWAMY MCA.

However, we can override operator precedence


by putting parentheses around your
expressions.
The following are precedence of operators in PHP
tt,-, (cast)
,*, %
t,
<,<<,=>,>
==, ===,!=
&&

=, t=, =, /=, *=, %=,=


and
XOr

Constarnts
changed during the
Aconstant is an identifier (name) for a simple value. The value cannot be
script.
constant name).
A valid constant name starts with a letter or underscore (no $ sign before the
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define) function.
Syntax
define(ame, value, case -insensitive)
Parameters:
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
The example below creates a constant with a case-sensitive name:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
2>

Flow Control Functions in PHP


(Decision making and branching statements)
It iscommon for scripts to evaluate conditions and change their behavior accordingly. These
decisions are what make your PHP pages dynamic - that is, able to change output according
to circumstances.
PHP includes the following switching flow controls.
1. The if Statement
2. Using the else Clause with the if Statement
3. Using the elseif Clause with the if Statement
. The switch Statement
5. Using the ?:Operator

TOgramming with PHP and MySQL For BSc VIh Sem Page | 23
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE.
1. The if Statement :
Syntax
True
if (expression) If(cond
ition)

1/ code to execute if the expression evaluates to true True block


Fail

Statement - x:

The if statement evaluates an expression found between parentheses. If this expression


results in a true value, the statement is executed. Otherwise, the statement is skipped
entirely.
Example
<?php
$t= date("H");
if ($t < "20") {
echo "Have a good day!";
?>
2. Using the else Clause with the if Statement: - flow chart
Syntax :
if (expression) Fail If(cond True
ition)
{
I/code to execute if the expression evaluates to true True block
false block

else

/code to execute in all other cases


Statement- x:

executed other wise


true block statements will be
> if the condition is true then the
false block statements will be executed. exit from the if else
one of the block then the program controller will after the
}After executing any immediately
remaining statements those are appeared
statement and execute the
if else statement.
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
Jelse (
echo "Have a good night!";

?>
Clause with the if Statement:
3. Using the elseif
Syntax
if (expression)
Page | 2F
Sem
PHP and MySQL For BSc V[h
Programming with
VYSHNAVI DEGREE COLLEGE, YMG.
U.KUMARA SWAMY MCA.

1/code to execute if the expression evaluates to true

elseif (another expression) Fail M(cond


ition1)
True

I/code to execute if the previous expression failed Fal flcond True


Block I sotements

/and this one evaluates to true Ition2)

Block 2 statements
Block 3 statements
else
Ext

//code to execute in all other cases


Statement-:

code is ignored. The


If the initial if expression does not evaluate to true, the first block of
elseif clause presents another expression for evaluation. If it evaluates to true, its
the
corresponding block of code is executed. Otherwise, the block of code associated with
else clause is executed. You can include as many elseif clauses as you want; and if you dont
need a default action, you can omit the else clause.
Example
<?php
$t= date("H");
if ($t< "10") {
echo "Have a good morning!";
}elseif ($t< "20") {
echo "Have a good day!";
else
echo "Have a good night!";
?>
4. The switch Statement ;
Entry
Syntax
switch (expression)
{ Kswitchlexpression)
case resultl:
| / execute this if expression results
in resultl cxpression=
break; constant-1
case result2: block-1
expression=
/execute this if expression constant-2
break; results in result2 block-2
default: (no match)
1/ execute this if no break defaull
default
1/has been encountered statement block
hitherto
Statement-x

The switch statement is an


alternative way of changing flow, based on
expression. A switch statement
selecting the correct one based on evaluates only one expression in a the evaluation of an
a specific bit of list of expressions,
default block will be matching code. If no match
executed. is found then

rogramming with PHP and MySQL For BSc


VIth Sem
Page | 25

You might also like