Вы находитесь на странице: 1из 34

About the Author

Ivan Bayross the human being

Open Source Varsity

The author Ivan Bayross is a 58 year old techno geek, mentor and friend. He is an M. Tech from Manchester University UK and has spent more than 30 years in the software industry rising through the ranks in the IT industry. Ivan Bayross started as a programmer, moved up to CIO, and is now the Chairman and Technology lead, in a software development house at Mumbai, India. He also owns several businesses in Mumbai India. He specializes in multi-tier, client / server, application development. Ivan Bayross is really a most approachable person and happily shares his skills with students and professionals alike.

Ivan Bayross the teacher


In the last ten years Ivan Bayross has put aside one day in the week when he guest lectures at a few MBA and Engineering colleges. If you would like him to guest lecture at your college, do get in touch.

Ivan Bayross the consultant


Additionally, being passionate about project management, he has been assisting a number of medium sized I.T. houses in stream lining their project management processes. Assisting them in any way he can to deliver their throughput to their clients in the shortest possible time and with the least bugs possible. Ivan Bayross is also very interested in Human Resource Management. HR is the most valuable resource in any company, more so today, because of the very competitive business environment in existence. He has assisted a number of medium sized companies in improving their Human Resource Management processes, helping them retain their talent, appropriately hire new talent, and cross train and improve their current employees to deliver a ton more than they currently do.

Ivan Bayross the author


Ivan Bayross is also an author, having authored and published over 68 books. He has the ability of taking a fairly complex programming or design concept and explaining this in simple to understand terms which has won him tons of fans among young information technology professionals.

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Table of Contents
PHP INTRODUCTION .......................................................................................................................................................... 4 WHAT IS PHP? ........................................................................................................................................................................ 4 HOW PHP WORKS? ................................................................................................................................................................ 4 WHAT ARE PHP BENEFITS? .................................................................................................................................................... 5 WHAT IS A PHP FILE? ............................................................................................................................................................. 5 WHY PHP? .............................................................................................................................................................................. 5 PHP DOWNLOAD .................................................................................................................................................................. 6 DOWNLOAD PHP ................................................................................................................................................................... 6 A COMMON TECHNIQUE TO FIND PHP {ANYTHING} USING GOOGLE ................................................................................. 6 PHP INSTALLATION .......................................................................................................................................................... 10 UNINSTALLATION PHP .................................................................................................................................................... 12 BINDING PHP TO APACHE .............................................................................................................................................. 15 CONFIGURING PHP TO WORK WITH APACHE: .................................................................................................................... 15 SYSTEM SETTINGS IN WINDOWS XP - PATH ......................................................................................................................... 16 TESTING THE APACHE AND PHP RELATIONSHIP ................................................................................................................. 18 BINDING PHP TO MYSQL ................................................................................................................................................ 20 INTRODUCTION: .................................................................................................................................................................... 20 THE BINDING PROCESS: ........................................................................................................................................................ 20 PHP / MYSQL - AT THE COMMAND PROMPT ........................................................................................................... 23 SETTING THE PATH TO THE PHP RUNTIME IN WINDOWS XP .............................................................................................. 23 CREATING PHP FILES: ........................................................................................................................................................... 25 Creating PHP file For MySQL Connection: ................................................................................................................. 25 Creating PHP File for MySQL Database: ..................................................................................................................... 26 The Structure Of The MySQL StudentMaster Table: ................................................................................................. 27 Creating PHP File for MySQL Database Table: .......................................................................................................... 28 Executing PHP file at Command Prompt: ................................................................................................................... 29 Verifying the Database and Table Is Created: ............................................................................................................. 31 MYSQL AND MYSQLI ........................................................................................................................................................ 34

Open Source Varsity. All Rights Reserved.

PHP Introduction
What is PHP?

Open Source Varsity

PHP is a widely used Open Source, general-purpose, Web server-side scripting language. PHP is especially suited for Web development. HTML can be embedded into PHP. PHP is often referred to as a Hypertext Preprocessor and is always used in conjunction with a web server such as Apache. PHP is actually an interpreter based, Hypertext (HTML) Pre Processor, created to run successfully with a host of Web servers. What PHP does is that it pre-processes the contents of any <filename.php> requested for by a Browser and delivered by the web server. Pre-processing of <filename.php> ensures that only pure HTML is delivered to the requesting Browser, HTML that has been correctly loaded with appropriate, well formatted and styled content. The fact that PHP runs at the web server has several benefits and a few drawbacks. PHP is actually a simple language, which has great power for manipulating, formatting and styling data and delivering this to a requesting Browser. PHP is not strongly typecast. PHP really has a very simple way of working with different types of memory variables. Memory variables are not declared to be of a specific type before they can be assigned a value to hold. If a number is assigned to a variable, then it just works. When the variable is later outputted to the browser, it just works. PHP takes care of converting the variable from an integer-type to a string-type, on the fly and automatically. PHP memory variables need not be pre-declared. They are simply created and assigned a value when required for use.

How PHP Works?


PHP sits between a Browser and a Web server. When you type in the URL of a PHP website in a Browsers address bar and hit the GO key, the Browser sends out a request to the Web server. The Web server then calls the PHP script named in the URL or perhaps index.php which can be visualized as a gateway script. The PHP environment at the Web server executes the script, the output of the PHP script is pure HTML which is then sent back to the requesting Browser as shown in Diagram 1.

Diagram 1

Open Source Varsity. All Rights Reserved.

What are PHP benefits?


PHP is a free, open source, Web server side scripting language.

Open Source Varsity

That means you don't have to pay thousands of dollars in licensing fee to acquire PHP. Best of all, it is easy to install. The most striking feature of it is that it is easy to learn. PHP is used by millions of people and developers around the world. There are thousands of websites on the internet which are written using PHP. One primary example is Yahoo! Bookmarks. PHP has an ever growing community. There are thousands of websites, forums and community websites dedicated to PHP. Hence, assistance for PHP issues is always available most often for Free or if charged for the charges are always pretty modest. PHP is a purpose built language for the internet. It is specifically designed to run on web servers to deliver dynamic web pages as quickly as possible, even on extremely high traffic websites. Security is a huge factor in todays' IT world. PHP has proven itself to be extremely secure and more than sufficient to run high risk sites such as banking or ecommerce applications. PHP has the huge advantage of being supported by virtually every server in the world. Unlike other languages that require expensive software to be installed on the server, PHP just requires Apache, a lightweight, free server side application that can be installed on any computer in the world. This compatibility and extremely economical running costs makes PHP the number one choice for businesses around the world.

What is a PHP File?


PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"

Why PHP?
PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side

Open Source Varsity. All Rights Reserved.

PHP Download
Download PHP

Open Source Varsity

Download the latest stable build of PHP from URL http://www.php.net/downloads.php .

A Common Technique to Find PHP {anything} Using Google


Open a browser window and enter http://www.google.com in the address bar and hit GO. In the Google search window that opens search for php download as shown in Diagram 1.

Diagram 1 In the Search results window Click on the php.net/downloads.php link as shown in Diagram 2.

Diagram 2

Open Source Varsity. All Rights Reserved.

When the php.net site opens in the Browser window click on the windows binary link as shown in Diagram 3.

Open Source Varsity

Diagram 3 Click on the zip file of Thread safe version of PHP as shown in Diagram 4.

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 4

Open Source Varsity. All Rights Reserved.

Save the zip file in the local drive of you system by clicking on the OK button of the window as shown in Diagram 5.

Open Source Varsity

Diagram 5 The download process of PHP is successfully finished.

Open Source Varsity. All Rights Reserved.

PHP Installation

Open Source Varsity

Navigate to the folder where the PHP executable .zip was downloaded to as shown in Diagram 6.

Diagram 6 Create a subdirectory in drive 'C' named C:\php as shown in Diagram 7.

Diagram 7 Extract all the files from the .zip file to C:\php as shown in Diagram 8.

10

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 8 The installation of PHP is complete.

11

Open Source Varsity. All Rights Reserved.

Uninstallation PHP
Uninstalling PHP from a system requires a few easy steps. Navigate to the drive where the php folder is located. Select the folder. Shift / Delete the folder from the drive as shown in Diagram 9.

Open Source Varsity

Diagram 9 PHP is now totally removed from the system. Next, navigate to C:\WINDOWS and search for a file named php.ini and select the file. Shift /Delete this file from C:\WINDOWS as shown in Diagram 10.

12

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 10 Next, navigate to C:\WINDOWS\system32 and search for a dll named libmysql.dll and select the file. Shift / Delete this file from C:\WINDOWS\system32 as shown in Diagram 11.

13

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 11 PHP has been completely removed from the system. Its as simple as this.

14

Open Source Varsity. All Rights Reserved.

Binding PHP to Apache


Note

Open Source Varsity

To know How to Install Apache Web Server refer to http://www.opensourcevarsity.com/apachebasics/l3apachewebserverinstallation

Configuring PHP to work with Apache:


To bind Apache and PHP together a few changes have to be made in Apache's httpd.conf. Apache's httpd.conf file is normally found in: C:\Program Files\Apache Software Foundation\Apache2.2\conf subdirectory. These are the entries that have to be made in Apache's httpd.conf file. Locate the IfModule mime_module section in the httpd.conf file Below the AddType application/x-gzip .gz .tgs add another entry as shown in Diagram 12. AddType application/x-httpd-php .php Take a look at the diagram below it could help you out

Diagram 12 Within Apache's httpd.conf file locate the LoadModule section, amd add another LoadModule entry.

15

Open Source Varsity. All Rights Reserved.

LoadModule php5_module "C:/php/php5apache2_2.dll" as shown in Diagram 13. Take a look at the diagram below it could help you out

Open Source Varsity

Diagram 13 Apache and PHP have been configured to work together

System settings in Windows XP - Path


Right click My Computer icon on the desktop and go to Properties. System Properties window open as shown in Diagram 14. My Computer > Property > Advance > Environment Variable >System Variable Path, and add C:\php as shown in Diagram 16;

16

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 14

Diagram 15

17

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 16 System settings in Windows XP completed

Testing the Apache and PHP relationship


Using any ASCII editor create a file named phpinfo.php The content of this file is a single line of code: <?php phpinfo(); ?> (type the line exactly as shown) Place this file in: C:\Program Files\Apache Software Foundation\Apache2.2\htdocs Restart Apache. Apaches Icon will be displayed in the Window's task bar. Its the first icon in the image below, with the tiny green triangle as shown in Diagram 17

Diagram 17 Simply double click this icon and from the Apache service monitor select 'Restart' as shown in Diagram 18

Diagram 18

18

Open Source Varsity. All Rights Reserved.

Execute the phpinfo.php file using any browser by typing in the following in its Address bar. http://127.0.0.1/phpinfo.php

Open Source Varsity

The following as shown in Diagram 19 should be displayed in the Browser window. This indicates that Apache and PHP are working together just fine.

Diagram 19 Apache and PHP have been installed and configured successfully.

19

Open Source Varsity. All Rights Reserved.

Binding PHP to MySQL


Introduction:

Open Source Varsity

The installation processes of PHP and MySQL occurs independent of each other. The operating system, in this case M.S. Windows, takes care of each installation process independent of the other. Hence when both products are installed one product really does not know that the other exists. Since PHP application code will be required to access MySQL database resources, its necessary to inform PHP that MySQL exists. Informing PHP that MySQL exists and configuring PHP to connect to MySQL successfully is known as binding PHP to MySQL.

The Binding Process:


In <driveletter>:\php locate a file named libmysql.dll. NOTE: We have installed PHP in C:\, hence all further content will refer to C:\. libmysql.dll was placed there during the installation process of PHP. Copy and paste this file into C:\windows\system32. Next in C:\php locate a file php.ini-recommended. Copy and paste this file into C:\windows. Rename the file php.ini-recommended to php.ini which in now within C:\windows. Make the following changes in the php.ini file Locate the extension_dir directive under Paths and Directories as shown in Diagram 20. Change this to: extension_dir = "C:\php\ext" NOTE: This directive needs to hold the path to where the ext folder exists within the PHP installation. Since PHP can be installed anywhere on the computers hard disk the value held in the extension_dir needs to be updated.

20

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 20 In the C:\windows\php.ini file locate the extension section, as shown in Diagram 21 Uncomment these 4 extensions, by deleting the ; at the start of the line. NOTE: Its a good idea to copy all four extensions to the very bottom of the extensions section and then uncomment them. This allows the extensions to be located quickly if they have to be commented again for any reason. These extensions are required by any internet application delivery framework. Please refer to Diagram 2. The extensions are: 1 2 3 4 Extensions php_gd2.dll php_curl.dll php_mysql.dll php_mysqli.dll Represents Permits the compression of images prior their dispatch to a requesting Browser. Required for URL redirection purposes, creating cookies and a ton of other stuff. Required for connecting to a MySQL db engine running in memory. This is an updated PHP library required to connect to a MySQL db engine running in memory. The php_mysqli.dll permits 30% to 40% faster data manipulation than mysql.dll.

21

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 21 The PHP binding with MySQL is complete along with gd2 and curl.

22

Open Source Varsity. All Rights Reserved.

PHP / MySQL - at the Command Prompt

Open Source Varsity

Before you attempt to execute any PHP program, ensure that the path php.exe (i.e. the PHP runtime) installed on your computer has been registered in the system settings, PATH variable of your computer. Here is how you can do this.

Setting the path to the PHP runtime in Windows XP

Right click My Computer on the desktop and go to Properties as shown in Diagram 22. The System Properties window opens as shown in Diagram 23.

Diagram 22 Then traverse - My Computer > Properties > Advanced > Environment Variable > System Variable Path. Click on Edit as shown in Diagram 23 and Diagram 24 and Add C:\php; as shown in Diagram 25.

Diagram 23

23

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 24

Diagram 25 The System settings in Windows XP are complete. In a previous tutorial, we have learnt how to execute a PHP program using a Browser i.e. interaction between PHP and MySQL. Here we will learn how to execute the same PHP files in a command window at the command prompt. Command line PHP script execution provides a quick way of testing PHP codespec without setting up a virtual domain and using a Web server to execute the PHP codespec. This helps you perform "build" and test tasks quickly and easily.

24

Open Source Varsity. All Rights Reserved.

Creating PHP files:

Open Source Varsity

Creating PHP file For MySQL Connection:


Go to any convenient logical drive on your hard disk and create a folder named studentdetail. In our example weve used G:\and within the drive created a folder named studentdetail as shown in Diagram 26.

Diagram 26 In the studentdetail folder, create a PHP file named config.php using any ASCII editor such as Notepad, Dreamweaver, Editplus or your favorite ASCII editor, as shown in Diagram 27. config.php will contain the codespec as shown in Example 1 below.

Diagram 27 NOTE: It is a good practice to keep your MySQL database connection details in a single file for ease of maintenance. It is necessary to connect to MySQL database engine running in memory. To be able to do this from within the PHP code spec you must make available a User name, Password and exactly where the MySQL db engine is running. In this case localhost indicates that the MySQL db engine is running on the same computer in which the PHP code snippet is being executed.

25

Open Source Varsity. All Rights Reserved.

Example 1 <?php

Open Source Varsity


$user = "root"; $pwd = "passwd"; $host = "localhost"; $con = @mysql_connect($host, $user, $pwd) or die("Connection Failed!"); if($con) { echo "Connection Established!"; } ?>

Copy paste the above codespec into the file named config.php and save this file in: G:\studentdetail There is a minimum of error handling added to the PHP code within config.php. If the connection to MySQL succeeds, a message Connection Established! will be displayed on the Command Window.

Creating PHP File for MySQL Database:


In the studentdetail folder, create a php file named createdb.php using any ASCII editor such as Notepad, Dreamweaver, Edit Plus or your favorite ASCII editor, as shown in Diagram 28. createdb.php will contain the codespec as shown in Example 2 below.

Diagram 28 To create a MySQL database (i.e. studentdb,), it is necessary to connect to MySQL database engine running in memory. To be able to do this within the PHP code spec include the config.php file once. The codespec to include the config.php file in createdb.php is as given in Example 2. The include_once() statement, as given in Example 2, includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

26

Open Source Varsity. All Rights Reserved.

Example 2: <?php include_once('config.php'); $qry="create database studentdb"; $result=mysql_query($qry); if($result) { echo("The MySQL Database Successfully Created!"); } else { echo("The MySQL Database Creation Failed!"); } ?>

Open Source Varsity

Copy paste the above codespec into the file named createdb.php and save this file in: G:\studentdetail There is a minimum of error handling added to the PHP code within created.php. If the connection to MySQL and the database creation succeeds, a message The MySQL Database Successfully Created will be displayed on the Command Window. If the connection to MySQL fails, a message Connection Failed! will be displayed on the Command Window. If the connection to MySQL database creation fails, a message The MySQL Database Creation Failed will be displayed on the Command Window. After creating the MySQL database - studentdb, which is an empty container, it is necessary to populate this empty container with table structure(s) to hold user data which can in turn be manipulated using PHP code. The first table we are going to create using PHP code within the MySQL database studentdb is the table StudentMaster. This MySQL table will be populated with student data to be manipulated later on demand using PHP codespec. Lets take a look at the structure of the MySQL table StudentMaster:

The Structure Of The MySQL StudentMaster Table:


Table Definition: Table Name: Column Definition: Column Name StudentID StudentName StudentDegree Speciality DOB StudentMaster Data Type INTEGER VARCHAR VARCHAR VARCHAR VARCHAR Width 3 25 25 35 15

27

Open Source Varsity. All Rights Reserved.

Table Description: Column Name StudentID StudentName StudentDegree Speciality DOB

Description of column contents Holds an identity number of the student Holds the name of the student Holds the degree acquired by the student Holds the specialty of the student Holds the Date of birth of the student

Open Source Varsity

Creating PHP File for MySQL Database Table:


In the studentdetail folder, create a php file named studentmaster.php using any ASCII editor such as Notepad, Dreamweaver, Editplus or your favorite ASCII editor, as shown in Diagram 29.

Diagram 29 Example 3: <?php include_once('config.php'); $db = "studentdb"; mysql_select_db($db) or die("Could not select database!"); echo "The MySQL Database Connection Established!"; $query = "CREATE TABLE StudentMaster( StudentID INTEGER(3), StudentName VARCHAR(25), StudentDegree VARCHAR(25), Speciality VARCHAR(35), DOB VARCHAR(15))"; if (@mysql_query($query)) { echo("Table created successfully."); } else { echo("Error creating table"); } ?>

28

Open Source Varsity. All Rights Reserved.

Copy paste the above codespec into the file named studentmaster.php and save this file in: G:\studentdetail

Open Source Varsity

If the MySQL connection gets established, a message Connection Established! will be displayed on the Command Window. There is a minimum of error handling added to the PHP code within studentmaster.php. If the database connection is established, a message The MySQL Database Connection Established! will be displayed on the Command Window. It will then create a table in a MySQL Db engine running in memory. If the query is executed successfully, it will display Table created successfully. on the Command Window.

Executing PHP file at Command Prompt:


To run this file on the command prompt, go to start -> Run. A window pops up. Next, in Open: , type in cmd as shown in Diagram 30. Click on OK as shown in Diagram 30.

Diagram 30 Next, type in the path of the file or the drive in which your file is saved and press Enter as shown in Diagram 31. For example: <system prompt> G: [Enter] You will notice that the prompt has now changed. This indicates that you are now in G:\ drive.

Diagram 31

29

Open Source Varsity. All Rights Reserved.

To take a look at the files in this directory at the < System Prompt > enter dir and press Enter. <system prompt> dir [Enter] A list of files is displayed as shown in Diagram 32. NOTE: The dir command displays the files in the current directory.

Open Source Varsity

Diagram 32 Navigate your prompt where your files are located as shown in Diagram 33.

Diagram 33 In order to create database, you need to run createdb.php at the command prompt. Enter php followed by the <filename.ext> at the command prompt as shown in Diagram 34. <system prompt> php createdb.php [Enter] As soon as you click on [Enter], the output is displayed Connection Established! The MySQL Database Successfully Created! . This means that the MySQL database is created successfully.

30

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 34 In order to create table(s) inside the database, you need to run studentmaster.php at the command prompt. Enter php followed by the <filename.ext> at the command prompt. <system prompt> php studentmaster.php [Enter] As soon as you click on [Enter], the output is displayed Connection Established! The MySQL Database Connection Established! Table created successfully. . This means that inside the MySQL database (i.e. studentdb), the MySQL table (i.e. studentmaster) has been created successfully as shown in Diagram 35.

Diagram 35

Verifying the Database and Table Is Created:

Log into MySQL as root with appropriate password as shown in Diagram 36. As soon as the system prompt changes to mysql> you are ready to verify the database created.

Diagram 36 Use the SHOW statement to find out what database(s) currently exist on the server as shown in Diagram 37.

31

Open Source Varsity. All Rights Reserved.

mysql> Show databases;

Open Source Varsity

Diagram 37 MySQL responds and displays a list of all the databases, which it controls as shown in Diagram 38. The studentdb database is successfully created.

Diagram 38 Before working with data held within a table it is necessary to inform the MySQL db engine which database holds the tables. The USE command specifies which database the MySQL db engine should set as active as shown in Diagram 39. mysql> Use studentdb;

Diagram 39 Use the SHOW statement to find out what table(s) currently exists on the database as shown in Diagram 40. The studentmaster table is successfully created in the database. mysql> Show tables;

32

Open Source Varsity. All Rights Reserved.

Open Source Varsity

Diagram 40

33

Open Source Varsity. All Rights Reserved.

MySQL and MySQLi

Open Source Varsity

MySQL is a relational database management system (or RDBMS) meaning that it is a database management system based on the relational model. This RDMS runs as its own server and provides multi-user access to multiple databases at once. The source code of MySQL is available under the terms set forth in the GNU General Public License as well as a plethora of proprietary agreements. Members of the MySQL community have created many different branches of the RDMS the most popular of which are Drizzle and MariaDB. As well as being the prototype of several branches, most free software projects that must have a full featured database management system (or DMS) use MySQL. MySQLi Extension (or simply known as MySQL Improved or MySQLi) is a relational database driver that is used mainly in the PHP programming language. It provides an interface to the already founded MySQL databases. It is quite literally an improved version of its predecessor, MySQL, which was simply a means to manage databases over servers. MySQL can be found in many web applications as the database component of a solution bundle (or LAMP) software stack. Its use can be seen widely in such popular web sites as Flickr, FaceBook, Wikipedia, Google, Nokia, and YouTube. Each one of these websites use MySQL for storage and the logging of user data. The code is comprised of the C and C++ languages and uses many different system platforms including Linux, Mac OS X, and Microsoft Windows. The MySQLi extension comes equipped with many benefits that compliment as well as improve those that were provided by its predecessor, MySQL. There are a few that are more prominent than others. These features that are meant to enhance the functionality of the MySQL (as well as provide an update to the database manager as a whole) are an object oriented interface, support for statements that have been previously prepared, support for a variety of statements, support for any kind of transaction that takes place, an enhanced level of debugging support, and an enhanced level of server support that is already embedded in the infrastructure of the database. As an RDBMS, it is not required that MySQL be shipped with GUI tools in order to administer the databases or manage the data therein. It is possible for users to use a command line tool or download MySQL Frontends from a variety of parties that have the software necessary and web applications to manage the databases, build the databases, and work with the data records.

34

Open Source Varsity. All Rights Reserved.