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

ONLINE TICKET RESERVATION SYSTEM FOR CINEMA HALLS

A PROJECT REPORT

Submitted by P.L.SRAVANTI Regd. No:-0801301043

In the partial fulfillment for the award of the degree Of BACHELOR OF TECHNOLOGY In COMPUTER SCIENCE ENGINEERING

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BIJU PATNAIK UNIVERSITY OF TECHNOLOGY May 2012

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE This is to certify that the project report ONLINE TICKET RESERVATION SYSTEMFOR CINEMA HALLSbeing submitted by P.L.SRAVANTI , in the partial fulfillment of requirement for the award of degree of BACHELOR OF TECHNOLOGY in CSE is a bonafide work carried out under my/our supervision.

Mrs. RAJALAXMI PRADHAN


HOD Department of CSE & IT Vignan Institute of Technology and Management Near Bhairabi,Brahmapur

Mr. AJAY KUMAR SAHU


INTERNAL GUIDE Lecturer Department of CSE & IT

External Examiner

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE This is to certify that P.L.SRAVANTI has successfully developed a project on ONLINE TICKET RESERVATION SYSTEM FORCINEMA HALLS under our guidance.Her skill set, knowledge on software and sincere effort has contributed towards successful completion of the project.

Mrs. RAJALAXMI PRADHAN


HOD Department of CSE & IT Vignan Institute of Technology and Management Near Bhairabi,Brahmapur

EXTERNAL SUPERVISOR

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

I hereby declare that the matter embodied in this report is originaland has not been submitted for the award of any other degree.

P.L.SRAVANTI
Department of CSE

Acknowledgement
I take this opportunity with much pleasure to thank all the people who have helped me through the course of my journey towards producing this thesis. I sincerely thank my thesis guide, Mr. Ajay Kumar Sahu, for his guidance, help and motivation. Apart from the subjects of my research, I learnt a lot from him, which I am sure will be helpful in different stages of my life. I would like to express my gratitude to my Project Coordinator Mr. Kailash Chandra Mishra for his review and many helpful comments.

I am especially grateful to my collegues for their assistance, criticisms and useful insights. I am thankful to all the other students of VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT with whom I share tons of funfilled memories. I would like to acknowledge the support and encouragement of my friends. My sincere gratitude also goes to all those whoinstructed and taught me through the years.

Finally, this thesis would not have been possible without the confidence, endurance and supportof my family. My family has always been a source of inspiration and encouragement. I wish to thank my parents, whose love, teachings and support have brought me this far.

Name of the Student

List of Figures
Serialno. Figures 1. (i) (ii) (iii) (iv) (v) (vi) 2. (i) (ii) (iii) 3. (i) (ii) (iii) 4. 5. Data Dictionary
Booking_info Movies States States_city Theatres Users

Page No.

48 48 48 49 49 49

Usecase Diagrams
Level 1 Level 2 Level 3

50 50 51

Data Flow Diagrams


Context Level Diagram Level 1 DFD Level 2 DFD

55 56 57 58 61-63

ER Diagram Output Screens

Table of Contents

Chapter No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Topics

Page No.

Introduction to the project Software Development Life Cycle System Analysis Introduction Initial Study Requirement and Feasibility analysis Software requirement specification PHP Language Session management using PHP Session management over web PHP session management Ajax Framework jQuery Database connectivity using PHP & PDO Structured Query Language Database Tables

1-2 3-4 5-7 8 9-12 13-14 15-16 17-18 19 20-21 22-25 26-29 30-45 46-47 48-49

16 17 18 19 20 21 22 23

Usecase Diagrams Data Flow Diagrams ER Diagram Online Cinema Ticket Booking Description Screenshots Coding Testing Conclusion References

50-51 52-57 58 59-60 61-63 64-76 77-79 80 81

1. Introduction to the Project


This project is aimed at developing an online ticket reservation system for Cinema Halls. The Ticket Reservation System is an Internet based application that can be accesses throughout the Net and can be accessed by anyone who has a net connection. This application will automate the reservation of tickets and Enquiries about availability of the tickets. This application includes email confirmation for the tickets. The users interested for booking tickets can perform following operations: Register with the web site. Request for ticket Book Ticket Check status of the ticket.

The administrator can perform following operations: Login to the web site. Create movies database. Update movies database. View request of the user then approve them.

System:
Modules: User Admin

User Options
Register This option allows candidates to register with the web. Request Using request option users can send a request to the system to book for ticket. Book The user can book the requested ticket

Administrative Options
Login The admin can login to the website. Add movies It can add movies to the movies database View request Using this option administrator can view the request posed by the user and grant them. Update Using this option administrator can add/edit/delete options in the movies database.

2. SOFTWARE DEVELOPMENT LIFE CYCLE


2.1 FEASIBILILTY ANALYSIS Feasibility study is done so that an ill-conceived system is recognized early indefinition phase. During system engineering, however, we concentrate ourattention on four primary areas of interest. This phase is really important asbefore starting with the real work of building the system it was very importantto find out whether the idea thought is possible or not. Economic Feasibility: An evaluation of development cost weighted againstthe ultimate income or benefit derived from the developed system. Technical Feasibility: A study of function, performance and constraints thatmay affect the ability to achieve an acceptable system. Operational Feasibility: A study about the operational aspects of the system.

2.2 ECONOMIC ANALYSIS


Among the most important information contained in feasibility study is CostBenefit Analysis and assessment of the economic justification for a computerbased system project. Cost Benefit Analysis delineates costs for the projectdevelopment and weighs them against tangible and intangible benefits of asystem. Cost Benefits Analysis is complicated by the criteria that vary withthe characteristics of the system to be developed, the relative size of theproject and the expected return on investment desired as part of companys strategic plan. In addition, many benefits derived from a computer-basedsystem are intangible (e.g. better design quality through iterativeoptimization, increased customer satisfaction through programmable controletc.)As this is an in-house project for the company, to be used for its ownconvenience and also it is not that big a project. So neither it requires a hugeamount of money nor any costly tools or infrastructure need to be set up forit.

2.3 TECHNICAL ANALYSIS


During technical analysis, the technical merits of the system are studied andat the same time collecting additional information about performance,reliability, maintainability and

predictability.Technical analysis begins with an assessment of the technical viability of theproposed system. What technologies are required to accomplished system function andperformance? What new materials, methods, algorithms or processes are required andwhat is their development risk? How will these obtained from technical analysis form the basis for anothergo/no-go decision on the test system? If the technical risk is severe, if models indicate that the desired function can not be achieved, if thepieces just wont fit together smoothly-its back to the drawing board. As the software is vary much economically feasible, then it is really importantfor it to be technically sound. The software will be build among: MS SQL SERVER as Back End ASP.NET as Front End

2.4 OPERATIONAL FEASIBILITY


The project is operationally feasible. This project is being made for theconvenience of the patients and doctors only. This system will greatly reduce a huge burden of doctors. So because of the above stated advantages theusers of the system will not be reluctant at all.

3. SYSTEM ANALYSIS INTRODUCTION: System analysis is the process of studying the business processors andprocedures, generally referred to as business systems, to see how they canoperate and whether improvement is needed.This may involve examining data movement and storage, machines andtechnology used in the system, programs that control the machines, peopleproviding inputs, doing the processing and receiving the outputs.

3.1 INVESTIGATION PHASE


The investigation phase is also known as the fact-finding stage or the analysis of the current system. This is a detailed study conducted with the purpose of wanting to fully understand the existing system and to identify the basicinformation requirements. Various techniques may be used in fact-finding and allfact obtained must be recorded.A thorough investigation was done in every effected aspect when determiningwhether the purposed system is feasible enough to be implemented. 3.1.1 INVESTIGATION As it was essential for us to find out more about the present system, weused the following methods to gather the information: 1. Observation: - Necessary to see the way the system works first hand. 2. Document sampling: - These are all the documents that are used in thesystem. They are necessary to check all the datathat enters and leaves the system. Questionnaires: - These were conducted to get views of the otheremployees who are currently employed in the system.

3.1.2 ANALYSIS OF THE INVESTIGATION

STRENGTHS OF THE SYSTEM 1. No complex equipment: - The equipment that is used is very simple and nospecial skills have to be mastered to be able to operatethe system. Therefore no training is required for theemployees. 2. Low cost: - There is little money spent in maintaining the presentsystem other than buying the necessary officeequipment and the ledgers.

3.2 CONSTRAINTS AND LIMITATIONS The constraints and limitation within a system are the drawbacks that occurduring the implementation of the system. These limitations and constraints cancrop up in almost every system; the most important fact is to find a way toovercome these problems.Software design is the first of three technical activities design, codegeneration, and test that are required to build and verify the software. Each activity transforms information in manner that ultimately results invalidated computer software.The design task produces a data design, an architectural design, aninterface design and component design.The design of an information system produces the details that clearlydescribe how a system will meet the requirements identified duringsystem analysis. The system design process is not a step by stepadherence of clear procedures and guidelines. When I started working onsystem design, I face different types of problems; many of these are due to constraints imposed by the user or limitations of hardware and software available. Some times it was quite difficult to enumerate that complexityof the problems and solutions thereof since the variety of likely problemsis so great and no solutions are exactly similar however the followingconsideration I kept in mind during design phased.

DESIGN OBJECTIVES:The primary objective of the design is to deliver the requirements asspecified in the feasibility report. These are the some of the objectives, which I kept in mind. Practicality: The system is quite stable and can be operatedby the people with average intelligence. Efficiency: I tried to involve accuracy, timeliness andcomprehensiveness of the system output. Cost: It is desirable to aim for the system with a minimum cost subject to the condition that it must satisfy the entire requirement. Flexibility: I have tried that the system should be modifiabledepending on the changing needs of the user. Such modifications shouldentail extensive reconstructing or recreation of software. It should also beportable to different computer systems. Security: This is very important aspect which I followed in thisdesigning phase and tried to covers the areas of hardware reliability,fallback procedures, and physical security of data.

4. INITIAL STUDY
INTRODUCTION: The first step in the Software Development Life Cycle (SDLC) is thepreliminary investigation to determine the feasibility of the system. Thepurpose of the preliminary investigation is to evaluate project requests. Itis not a design study nor does it include the collection of details todescribe the business system in all aspect. Rather it is the collection of theinformation that helps committee members to evaluate the merits of theproject request and make an informed judgment about the feasibility of the proposed project.The preliminary investigation should accomplish the following objectives.

Clarify and understand the project request. Determine the size of the project. Assess costs and benefits of alternative approaches. Determine the technical and operational feasibility of alternative approaches. Report the findings to management; with recommendations outlining the acceptance or rejection of the proposal.

5. REQUIREMENT AND FEASIBILTY ANALYSIS


INTRODUCTION: What Is A Feasibility Study?Prior to stating whether the system we have to develop is feasible or not webelieve that we should emphasize on what is implied by the word Feasibility.Feasibility is the measure of how beneficial or practical the development of thesystem will be to the organization. It is a preliminary survey for the systemsinvestigation. It aims to provide information to facilitate a later indepthinvestigation.The report produced at the end of the feasibility study contains suggestions andreasoned arguments to help management decide whether to commit furtherresources to the proposed project.Within the scheduled duration we were assigned to study both the positive andnegative aspects of the current manual system, in which we have come up witha number of drawbacks that prevent the progress of the clinic if it is continued tofunction manually.Having gone through all measures of feasibility we report to the management tofigure out if the objectives of the new system are met. For e.g. - Is the system within the budget allowed for it? -Will the organizations needs, be met by the new proposed system asOriginally envisaged? If and when the objectives of the system are met and the new system isapproved, then the more specific details in the proposal should be consideredand approved. TYPES OF FEASIBILITY: There are various measures of feasibility that helps to decide whether aparticular project is feasible or not. These measures includeOperational Feasibility Technical Feasibility Economical and Financial Feasibility Each of these types will be explained in detail throughout the project report.

OPERATIONAL FEASIBILITY A proposed system is beneficial only if it can be turned into an informationsystem that will meet the operational requirements of an organization. A systemoften fails if it does not fit within existing operations and if users resist thechange.Important issues a systems developer must look into are: Will the new system be used if implemented in anorganization? Are there major barriers to implementation or is proposedsystem accepted without destructive resistance? The whole purpose of computerizing the Placement System is to handle the work much more accurately and efficiently with less time consumption. There will be additional work to be completed, because now the students and the companiescan update their resumes and profiles online. Their database is maintained separately.

Compared to the semi-computerized system the chances of avoiding errors in acomputerized system is much higher because the user need not stress himself unnecessarily resulting in recklessness. Unlike the semi-computerized systemthere would be backup data for all the information concerning the dailytransactions occurred within the organization . If we are considering the performance and response time for each task, it is verymuch faster since there is less paper work to be completed. When entering datainto the system to relieve the user from additional work and typing incorrectdata, the system provides options such as combo boxes, check boxes, optionbuttons and etc. if the users type in incorrect data they would be informedimmediately about the error by the error detection control.

Another important fact to be regarded is the security control, which is handled bythe system. Since data regarding each student and the company is confidential,security is a key issue. Information falling into the wrong hands could jeopardizethe entire organization. Unlike in semi-computerized systems the proposedsystem offers adequate 10

control to protect the organization against fraud andembezzlement and guarantees the accuracy and security of data andinformation. This is handled by the system providing each department andindividuals with separate login names and passwords.

The new system is more user-friendly, which enables the end-user to completehis/her work efficiently and accurately with interest. After taking the above factinto consideration we can state the operating of the proposed system within theorganization is feasible.

In this phase of the feasibility study the following two main topic Technical Performance Aspect Acceptance within the organization

Technical performance aspect is explained in the technical feasibility report andthere is no new information is needed in this to explain it again, but as for theacceptance within the organization the following points are important and thoseare explained according to the topics 1. Whether the system provides right information to the right place.In the current system which is the semi computerized system the informationmay be lost in the process of sending from one place to another. This is mainlydue to human interaction in the process of the transferring information from oneplace to another. 2. Whether the new system affect the current users in the systemThe new proposed system will affect the users in the following areas Accuracy Efficiency Productivity Robustness Lesser time consuming.

11

SYSTEM SECURITY System security is a vital aspect when it comes to developing a system.The system should ensure the facility of preventing unauthorized personnel from accessing the information and the data within the system.The system should provide total protection for each users information sothat the integrity of data is sustained and also prevent hackers fromhacking the system. The proposed system ensures the security and the integrity of data. This is doneby providing a password login system for each authorized users. And for examplethe System Administrator has access to all kinds of information. By providing this facility information is properly managed and information isprotected. For example the system administrators day to day tasks are lessenedand easier because he doesnt have to have a constant eye on the system andworry about hackers hacking the system.

ECONOMIC AND FINACIAL FEASIBILITY In making recommendations a study of the economics of the proposedsystem should be made. The proposed system must be justifiable in termsof cost and benefit, to ensure that the investment in a new/changedsystem provide a reasonable return. Cost-benefit analysis of information is complicated by the fact that many of thesystems cost elements are poorly defined and that benefit can often be highlyqualitative and subjective in nature.In our proposed system various costs are evaluated. Even though finding out thecosts of the proposed project is difficult we and assume and estimate the costsand benefits as follows: According to the computerized system we propose, the costs can be brokendown to two categories. 1. Costs associated with the development of the system 2. .2. Costs associated with operating the system.

12

6. Software Requirement Specification


The software requirement specification is produced at the culmination of the analysis task. The function and performance allocated to software aspart of system engineering are refined by establishing a completeinformation description, a detailed functional description, a representationof system behavior, an indication of performance requirement and designconstraints appropriate validation criteria, and other information pertinentto requirement.The introduction to software requirements specification states the goalsand objectives of the software, describing it in the context of the computerbased system.The Information Description provides a detailed description of the problemthat the software must solve. Information content, flow and structure aredocumented.A description of each function required to solve the problem is presentedin the Functional Description. Validation Criteria is probably the most important and ironically the mostoften neglected section of the software requirement specification.Software requirement specification can be used for different purpose. Hereare the major uses.not clearly understood by the developer. If this is the case, a carefulanalysis involving much interaction with the user should be devoted toreaching a clear statement of requirements, in order to avoid possiblemisunderstandings.Sometimes, at the beginning of a project, even the user has no clear ideaof what exactly the desired product is. Think for instance of userinterface , a user with no previous experience with computer productsmay not appreciate the difference between , say menu driven interactionand a command line interface. Even an exact formation of system functions and performance may be missing an initial description produced by an inexperienced user.

13

A statement of the requirements for the implementation:


Specifications are also used as a reference point during productimplementation. In fact, the ultimate goal of the implementation is to builda product that needs specification. Thus the implementers usespecifications during design to make design decisions and during theverification activity to check that the implementation compiles with specifications.

14

7. PHP LANGUAGE:
PHP is a programming language for building dynamic, interactive Web sites. As a general rule, PHP programs run on a Web server, and serve Web pages to visitors on request. One of the key features of PHP is that you can embed PHP code within HTML Web pages, making it very easy for you to create dynamic content quickly. What exactly does the phrase dynamic, interactive Web sites mean? A dynamic Web page is a page whose contents can change automatically each time the page is viewed. Contrast this with a static Web page, such as a simple HTML file, which looks the same each time its displayed (at least until the page is next edited). Meanwhile, an interactive Web site is a site that responds to input from its visitors. A Web forum is a good example users can post new messages to the forum, which are then displayed on the site for all to see. Another simple example is a contact us form.where visitors interact with the page by filling out and sending a form, which is then emailed to the Webmaster. PHP stands for PHP: Hypertext Preprocessor, which gives you a good idea of its core purpose: to process information and produce hypertext (HTML) as a result. (Developers love recursive acronyms, and PHP: Hypertext Preprocessor is a good example of one.) PHP is a server - side scripting language , which means that PHP scripts, or programs, usually run on a Webserver. (A good example of a client - side scripting language is JavaScript, which commonly runs within a Web browser.) Furthermore, PHP is an interpreted language a PHP script is processed by the PHP engine each time its run. The process of running a PHP script on a Web server looks like this: 1. A visitor requests a Web page by clicking a link, or typing the page s URL into the browser s address bar. The visitor might also send data to the Web server at the same time, either using a form embedded in a Web page, or via AJAX (Asynchronous JavaScript And XML). 2. The Web server recognizes that the requested URL is a PHP script, and instructs the PHP engine to process and run the script. 3. The script runs, and when its finished it usually sends an HTML page to the Web browser, which the visitor then sees on their screen.The interesting stuff happens when a PHP script runs. Because PHP is so flexible, a PHP script can carry out any number of interesting tasks, such as: Reading and processing the contents of a Web form sent by the visitor Reading, writing, and creating files on the Web server 15

Working with data in a database stored on the Web server Grabbing and processing data from other Web sites and feeds Generating dynamic graphics, such as charts and manipulated photos And finally, once its finished processing, it can send a customized HTML Web page back to the visitor.

Why Use PHP ?


One of the best things about PHP is the large number of Internet service providers (ISPs) and Web hosting companies that support it. Today hundreds of thousands of developers are using PHP, and its not surprising that there are so many, considering that several million sites are reported to have PHPinstalled. Another great feature of PHP is that it s cross - platform you can run PHP programs on Windows, Linux, FreeBSD, Mac OS X, and Solaris, among others. What s more, the PHP engine can integrate with all common Web servers, including Apache, Internet Information Server (IIS), Zeus, and lighttpd. This means that you can develop and test your PHP Web site on one setup, then deploy it on a different type of system without having to change much of your code. Furthermore, its easy to move your PHP Website onto another server platform, if you ever need to.

16

8. SESSION MANAGEMENT
Cookies Cookies are often used to store application state in a web browser. As with data sent with the GET or POST methods, cookies are sent with HTTP requests made by a browser. A cookie is a named piece of information that is stored in a web browser. A browser can create a cookie using JavaScript, but a cookie is usually sent from the web server to the client in the Set-Cookie header field as part of an HTTP response. A cookie can have a date and time at which it expires. The browser includes the cookie in requests up until that date and time. If no expiry date is given, the cookie is remembered only while the browser is running. Cookies that are kept only while the browser is running are known as session cookies. A domain limits the sites to which a browser can send the cookie. If no domain is set, the browser includes the cookie only in requests sent to the server that set the cookie. Browsers don't include the cookie in requests for resources that aren't in the specified path. This is useful if only part of a web site requires that a cookie be sent. For example, if the path is set to /admin, requests for resources in that path, such as http://localhost/admin/home.php include the cookie, while requests for resources in other paths, such as http://localhost/winestore/home.php, do not. A cookie can also be marked as secure, instructing the browser to send the cookie only when using a secure connection through the Secure Sockets Layer protocol. This prevents sensitive data stored in a cookie from being transmitted in an insecure form. Cookies can be included in an HTTP response using the header( ) function; however, the developer needs to know how to encode the cookie name, value, and the other parameters described earlier in the Set-Cookie header field. To simplify cookie creation, PHP provides the setcookie( ) function that generates a correct header field.

When an HTTP request that contains cookies is processed, PHP makes the values of the cookies available to the script in the global associative array $HTTP_COOKIE_VARS. If register_globals is enabled, a variable with the name of the cookie is also initialized by PHP; the register_globals feature in the php.ini file is discussed in Chapter 5.Example 8-1 tests to see if the variable $count has been set from a cookie, and either sets the value to 0 or increments 17

$count accordingly. The script also creates a cookie named start, with the value set to the current time, when the $count is set to 0. The cookie start is set only at the beginning of this stateful interaction. Cookies can be used for simple applications that don't require complex data to be kept between requests. However, there is a limit on the number and size of cookies that can be set: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size. Also, there are arguments about both the privacy and the security of applications that use cookies, and users often disable cookie support in their browsers.

18

9. SESSION MANAGEMENT OVER WEB


Storing the state in the web server--the middle tier--can solve the problem of increased request size and protect the state of an application from accidental or intentional changes a user might make.

A session is a way to identify and manage the state--the session variables--for a particular user. When a user sends an HTTP request, the middle tier must process the current request in the context of the user's session. When a session is started, the client is given a session identifier-often a cookie--that is included with subsequent requests to the server. The server uses the session identifier to locate the corresponding session before processing the request.

Rather than storing all the variables needed to maintain state and include them with each request, the browser stores a single session identifier that finds and initializes the variables stored on the server. The session identifier is like the ticket given at a cloak room. The ticket is much easier to carry around and ensures that the holder gets her own hat and coat.

One implication of storing session variables in the middle tier is that data needs to be stored for each session. The question is, for how long? Because HTTP is stateless, there is no way to know when a user has finished with a session. Ideally, the user logs out of an application, and the logout script ends the session. However, because a server can never be sure if a user is still there, the server needs to clean up old sessions that have not been used for a period of time. This last point is important, because sessions consume resources on the server, and dormant sessions may present a security risk. In summary, there are three characteristics session management over the Web must exhibit: 1. Information or state must be stored. For example, a selected bottle of wine in a shopping cart, a customer name, or a credit card number must be maintained across multiple HTTP requests. 2. Each HTTP request must carry an identifier that allows the server to process the request in the context of the stored state. For example, when an order is submitted, it must be processed with the correct items and customer details. 3. Sessions need to have a timeout. Otherwise, if a user leaves the web site, there is no way the server can tell when the session should end. 19

10. PHP Session Management


With the release of PHP4, session management was introduced as an extension to the PHP language. PHP provides several session-related functions, and developing applications that use PHP sessions is straightforward. The three important features of session management are mostly taken care of by the PHP scripting engine.

Starting a Session PHP provides a session_start( ) function that creates a new session and subsequently identifies and establishes an existing one. Either way, a call to the session_start( ) function initializes a session.

The first time a PHP script calls session_start( ), a session identifier is generated, and, by default, a Set-Cookie header field is included in the response. The response sets up a session cookie in the browser with the name PHPSESSID and the value of the session identifier. The PHP session management automatically includes the cookie without the need to call to the setcookie( ) or header( ) functions.

The session identifier (ID) is a random string of 32 hexadecimal digits, such as fcc17f071bca9bf7f85ca281094390b4. As with other cookies, the value of the session ID is made available to PHP scripts in the $HTTP_COOKIE_VARS associative array and in the $PHPSESSID variable.

When a new session is started, PHP creates a session file. With the default configuration, session files are written in the /tmp directory using the session identifier, prefixed with sess_, for the filename. If a call is made to session_start( ), and the request contains the PHPSESSID cookie, PHP attempts to find the session file and initialize the associated session variables as discussed in the next section. However, if the identified session file can't be found, session_start( ) creates an empty session file.

20

Using Session Variables Variables need to be registered with the session_register( ) function that's used in a session. If a session has not been initialized, the session_register( ) function calls session_start( ) to open the session file. Variables can be registered--added to the session file--with the session_register( ) . Once registered, session variables are made persistent and are available to scripts that initialize the session. PHP tracks the values of session variables and saves their values to the session file; there is no need to explicitly save a session variable before a script ends. Variables can be removed from a session with the session_unregister( ) function call; again, the name of the variable is passed as the argument, not the variable itself. A variable that is unregistered is no longer available to other scripts that initialize the session. However, the variable is still available to the rest of the script immediately after the session_unregister( ) function call.

Scripts that initialize a session have access to the session variables through the associative array $HTTP_SESSION_VARS, and PHP automatically initializes the named session variables if register_globals is enabled.

Session variables can be of the type Boolean, integer, double, string, object, or arrays of those variable types. Care must be taken when using object session variables, because PHP needs access to the class definitions of registered objects when initializing an existing session. If objects are to be stored as session variables, you should include class definitions for those objects in all scripts that initialize sessions, whether the scripts use the class or not.

PHP stores session variables in the session file by serializing the values. The serialized representation of a variable includes the name, the type, and the value as a stream of characters suitable for writing to a file.

21

11. Ajax

Framework

An Ajax framework is a framework that helps to develop web applications that use Ajax, a collection of technologies used to build dynamic web pages on the client side. Data is read from the server or sent to the server by JavaScript requests. However, some processing at the server side may be required to handle requests, such as finding and storing the data. This is accomplished more easily with the use of a framework dedicated to process Ajax requests. The goal of the framework is to provide the Ajax engine and associated server and client-side functions. This Ajax engine is intended to suppress the delays perceived by the user when a page attempts to access the server. A framework eases the work of the Ajax programmer at two levels: on the client side, it offers JavaScript functions to send requests to the server. On the server side, it processes the requests, searches for the data, and transmits them to the browser. Some frameworks are very elaborate and provide a complete library to build web applications.

Types of frameworks
Ajax frameworks can be loosely grouped into categories according to the features they offer and the skills required of the user:

Direct Ajax frameworks


These frameworks require HTML, CSS and Ajax expertise: a developer is expected to author pages directly in HTML, and framework APIs deal directly with HTML elements. Cross-browser APIs are provided for a variety of purposes, commonly including communications, DOM manipulation, event handling, and sizing/moving/animating HTML elements. These frameworks are generally smaller. They are commonly used for a web site such as a shopping experience, but not for a web application such as web-based email, at least not without further frameworks layered on top.

22

Indirect Ajax frameworks


These frameworks are based on compiler technology, where, instead of writing direct Ajax and Javascript, a high-level language is used instead, along with a compiler that turns the high-level language into Javascript. Indirect frameworks therefore require knowledge of the high-level language, CSS and HTML, and do not necessarily require a great deal of Ajax or Javascript expertise. The Indirect frameworks are typically accompanied by convenient libraries, modules and classes (written in the high-level language) that take care of communications, DOM manipulation including HTML element manipulation, and event handling. The advantages of Indirect Ajax frameworks - compilation to Javascript - are:

The developer can effectively create their own Ajax framework using programming concepts and techniques appropriate to the high-level language (e.g. modules and classes) which are simply not present in the Javascript language.

the to-javascript compiler can enforce strong type-checking and definition rules that standalone javascript does not

A developer can program the web front-end in the same programming language as that which the server-side code is written in.

The high-level web widget sets of the Indirect Ajax frameworks have far more in common with Desktop widgets than they do with "traditional" web development.

The framework, through the compiler, can create code that takes care of browser incompatibilities at run-time, and thus can present a common browser-independent API to the developer.

Indirect Ajax frameworks have distinct and significant advantages:

Compared to Ajax component frameworks, the developer can use the available base class widgets to create their own widgets, in the high-level language with which they are familiar, instead of trying to get to grips with javascript.

The developer is therefore neither burdened by the bloat of Ajax component frameworks nor bound by their rigidity.

23

The developer has both the advantages of the Ajax component frameworks, and their associated widgets, as well as the advantages of the freedom of Direct Ajax frameworks.

Indirect Ajax frameworks can be used to even greater effect in combination with a Server-driven framework (typically using JSONRPC or XMLRPC).

Interestingly, Python and Ruby are a good match for compilation to Javascript, and a far better match than Java, because Java (and Java Virtual Machines) lack some of the run-time dynamic capabilities of Javascript, Python and Ruby. Fortunately for Java (and for GWT), it's Java that is less dynamically capable than Javascript. The "class" capability of these high-level languages can be emulated using Javascript "prototype".

Ajax component frameworks


These frameworks offer pre-built components, such as tabbed panes, which automatically create and manage their own HTML. Components are generally created via JavaScript or XML tags, or by adding special attributes to normal HTML elements. These frameworks are generally larger, and intended for web applications rather than web sites. Some component frameworks require the developer to have extensive HTML/CSS/Ajax experience and to do cross-browser testing. For example, grids, tabs, and buttons may be provided, but user input forms are expected to be authored directly in HTML/CSS and manipulated via Ajax techniques. Other frameworks provide a complete component suite such that only general XML and/or JavaScript abilities are required. Ajax component frameworks can enable more rapid development than direct Ajax frameworks, but with less control, hence it is key that an Ajax component framework provides the following:

customization APIs, e.g., an event that fires when the user stops editing within a grid skinning facilities, where appearance can be changed without affecting behavior or layout programmatic control, e.g., dynamically adding tabs or dynamically creating components based on user data

extensibilitycreation of new components based on other components, so that the benefits of a component-based framework are not lost 24

Server-driven Ajax frameworks


Several frameworks offer a server-side component-based development model with some degree of Ajax support. Components are created and manipulated on the server using a server-side programming language. Pages are then rendered by a combination of server-side and client-side HTML generation and manipulation. User actions are communicated to the server via Ajax techniques, server-side code manipulates a server-side component model, and changes to the server component model are reflected on the client automatically. These frameworks offer familiarity and efficiency for server-side developers at the possible expense of power and performance. Ajax frameworks that handle presentation completely within the browser may offer greater responsiveness if they handle more user interactions without server involvement. In a server-driven model, some UI interactions can react slowly, for example when an input field is dynamically enabled based on server-requests. Furthermore, serverdependent Ajax frameworks cannot offer offline support. The approach is still popular for situations where the benefits of a full Ajax architecture can't be captured or where server interaction is needed anyway. Extending a framework may require the developer to understand which parts of the presentation are handled on the client vs on the server, and to code in JavaScript/Ajax as well as server-side code (an issue which can be overcome through the use of an Indirect Ajax framework, by choosing an Indirect Ajax framework with a compiler that accepts the same language as the server-side code).

25

12. jQuery jQuery is great library for developing ajax based application. jQuery is great library for the JavaScript programmers, which simplifies the development of web 2.0 applications. You can use jQuery to develop cool web 2.0 applications. jQuery helps the programmers to keep code simple and concise. The jQuery library is designed to keep the things very simple and reusable.

jQuery library simplifies the process of traversal of HTML DOM tree. You can use jQuery to handle events, perform animation, and add the ajax support into your web applications with ease.

Why jQuery?
You can use simple JavaScript to perform all the functions that jQuery provides. Then why jQuery? The jQuery library is providing many easy to use functions and methods to make rich applications. These functions are very easy to learn and even a designer can learn it fast. Due to these features jQuery is very popular and in high demand among the developers. You can use jQuery in all the web based applications irrespective of the technology.

jQuery is java script and can be used with JSP, Servlets, ASP, PHP, CGI and almost all the web programming languages.

The jQuery code is very simple and easy to learn.

Features of jQuery
Query have lot of functionalities but some of the key features are given below :

Selection of DOM elements : The jQuery selector provide us capability to select DOM elements so that we can add functionality to them using methods of jQuery. It is using CSS 3.0 syntax which provide us freedom to select one or more elements. Using CSS , you can select element by id, class and collaborate with events to increase it's functionality.

26

The wrapped set The selected elements reside inside a object known as wrapped set. It contain all the selected DOM elements, it has array like structure. You can traverse through this like an array and can select elements using index.

Events jQuery provide simplified event handling, You can easily bind and unbind events and for supported browsers it also provide a normalized event model due to this it is very easy to handle events.When any event occurs , it is called under the context of the event that triggered it.

Extensibility through plug-ins The jQuery architecture provide us freedom to extend functionality using plug-ins . The plug-ins are easy to use and easy to clip with your page. You just need to set parameters to use these jQuery plug-ins and also need to include plug-in file. Some the main jQuery plug-ins are : 1. XML and XSLT tools 2. Cookie handling 3. Datagrids 4. Drag and drop events. 5. odal windows 6. Dynamic lists 7. Webservices 8. Ajax helpers 9. Even a jQuery-based Commodore 64 emulator.

Cross-browser support In JavaScript, the DOM implementations for event handling vary considerably between browsers. Where as jQuery providing a normalized event model for all supported browsers that makes it very easy to handle events.

27

Ajax support AJAX stands for Asynchronous JavaScript and XML . Using AJAX we can connect to database and also can fetch the data from the server's database without refreshing the page. JQuery have very effective AJAX methods library to extend the functionality of AJAX.

Compatibility with languages The jQuery script can be used with nearly all the web languages. Some of Frequently used languages with jQuery are given below:

1. PHP 2. JSP 3. ASP 4. Servlet 5. CGI

HOW TO USE jQuery The jQuery library helps the developer to develop rich internet applications. This is one of the most used framework on the web. Its easy to learn and use language. Here is the highlights of jQuery: jQuery is a JavaScript based Library that runs in browser. Its is client side ajax framework. jQuery simplifies the development of ajax based application using JavaScript programming language. jQuery is easy to learn and use language. Programmer's can learn it easily. Lot's of support. There are many examples and tutorials available on internt.

The jQuery is designed to do more work in less coding. It's very easy to work with jQuery. It support all the serverside web application development technologies. You can use JSP,Servlets, Struts, Spring MVC, ASP, .NET, CGI, PHP, Perl etc. as server-side language and user jQuery to dynamically fetch data from the server.

So, jQuey is very useful tool. Let's see how it works and we can use it in programming. 28

Traditionally developer's are using Window.onload() function to initiate some action on page load. There is one drawback with this function. It does not fires until all the images including the advertisement banner are loaded. So, window.onload() can be painfully slow. The jQuery provides the solution for this problem. The $(document).ready(function(){}) solves the issue. It is fired once the Document Object Model is ready. So, you can use this to run any type of JavaScript to suite your business needs.

29

13. Database Connectivity Using PHP and PDO

PHP makes it easy to write scripts that access databases, enabling you to create dynamic web pages that incorporate database content. PHP includes several specialized database-access interfaces that take the form of separate sets of functions for each database system. There is one set for MySQL, another for Inter-Base, another for PostgreSQL, and so forth. However, having a different set of functions for each database makes PHP scripts non-portable at the lexical (source code) level. For example, the function for issuing an SQL statement is named mysql_query(), ibase_query(), or pg_exec(), depending on whether you are using MySQL, InterBase, or PostgreSQL. In PHP 5 and up, we can avoid this problem by using the PHP Data Objects (PDO) extension. PDO supports database access in an engine-independent manner based on a two-level architecture: The top level provides an interface that consists of a set of classes and methods that is the same for all database engines supported by PDO. The interface hides engine-specific details so that script writers need not think about which set of functions to use. The lower level consists of individual drivers. Each driver supports a particular database engine and translates between the top-level interface seen by script writers and the database-specific interface required by the engine. This provides you the flexibility of using any database for which a driver exists, without having to consider driver-specific details.

Writing PDO Scripts:


Scripts that use the PDO interface to access MySQL generally perform the following operations: 1. Connect to the MySQL server by calling new PDO() to obtain a database handle object. 2. Use the database handle to issue SQL statements or obtain statement handle objects. 3. Use the database and statement handles to retrieve information returned by the statements. 4. Disconnect from the server when the database handle is no longer needed.

30

Connecting to and Disconnecting from the MySQL Server:


To establish a connection to a MySQL server, specify a data source name (DSN) containing connection parameters, and optionally the username and password of the MySQL account that you want to use. To connect to the MySQL server on the local host to access the test database with a username and password of test user and testpass, the connection sequence looks like this:

$dbh = new PDO("mysql:host=localhost;dbname=test", "testuser", "testpass");

For MySQL, the DSN is a string that indicates the database driver (mysql), and optionally the hostname where the server is running and the name of the database you want to use. Typical syntax for the DSN looks like this:

mysql:host=host_name;dbname=db_name

The default host is localhost. No default database is selected if dbname is omitted. The MySQL driver also recognizes port and unix_socket parameters, which specify the TCP/IP port number and Unix socket file pathname, respectively. If you use unix_socket, do not specify host or port. For other database engines, the driver name is different (for example, pgsql for PostgreSQL) and the parameters following the colon might be different as well. When you invoke the new PDO() constructor method to connect to your database server, PDO determines from the DSN which type of database engine you want to use and acesses the lowlevel driver appropriate for that engine. This is similar to the way that Perl or Ruby DBI scripts reference only the top-level DBI module; the connect() method provided by the top-level module looks at the DSN and determines which particular lower-level driver to use. If new PDO() fails, PHP throws an exception. Otherwise, the constructor method returns an object of the PDO class. This object is a database handle that you use for interacting with the database server until you close the connection. An alternative to putting the connection code directly in your script is to move it into a separate file that you reference from your main script. For example, you could create a file pdo_testdb_connect.php that looks 31

like this:

<?php # pdo_testdb_connect.php - function for connecting to the "test" database function testdb_connect () { $dbh = new PDO("mysql:host=localhost;dbname=test", "testuser", "testpass"); return ($dbh); } ?> Then include the file into your main script and call testdb_connect() to connect and obtain the database handle: require_once "pdo_testdb_connect.php"; $dbh = testdb_connect (); This approach makes it easier to use the same connection parameters in several different scripts without writing the values literally into every script; if you need to change a parameter sometime, just change pdo_testdb_connect.php. Use of a separate file also enables you to move the code that contains the connection parameters outside of the web servers document tree. That has the benefit of preventing it from being displayed literally if the server becomes misconfigured and starts serving PHP scripts as plain text. Any of the PHP file-inclusion statements can be used, such as include or require, but require_once prevents errors from occurring if any other files that your script uses also reference pdo_testdb_connect.php. When youre done using the connection, close it by setting the database handle to NULL:

$dbh = NULL;

After that, $dbh becomes invalid as a database handle and can no longer be used as such. If you do not close the connection explicitly, PHP does so when the script terminates.

32

While the database handle is open and you are using it to issue other PDO calls, you should arrange to handle errors if they occur. You can check for an error after each PDO call, or you can cause exceptions to be thrown. The latter approach is simpler because you need not check for errors explicitly; any error raises an exception that terminates your script. If you enable exceptions, you also have the option of catching them yourself instead of allowing them to terminate your script. By doing this, you can substitute your own error messages for the defaults, perform cleanup operations, and so on. To enable exceptions, set the PDO error mode as follows after connecting:

$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

That statement is something you could add to the testdb_connect() function if you want the error mode to be set automatically whenever you connect.

Issuing Statements
After obtaining a database handle by calling new PDO(), you can use it to execute SQL statements: For statements that modify rows and produce no result set, pass the statement string to the database handle exec() method, which executes the statement and returns an affected-rows count: $count = $dbh->exec ("some SQL statement"); For statements that select rows and produce a result set, invoke the database handle query() method, which executes the statement and returns an object of the PDOStatement class:

$sth = $dbh->query ("some SQL statement");

This object is a statement handle that provides access to the result set. It enables you to fetch the result set rows and obtain metadata about them, such as the number of columns. To illustrate how to handle various types of statements, the following discussion shows how to create and populate a table using CREATE TABLE and INSERT (statements that return no result set). Then it uses SELECT to generate a result set.

33

Issuing Statements That Return No Result Set


The following code uses the database handle exec() method to issue a statement that creates a simple table animal with two columns, name and category:

$dbh->exec ("CREATE TABLE animal (name CHAR(40), category CHAR(40))");

After the table has been created, it can be populated. The following example invokes the exec() method to issue an INSERT statement that loads a small data set into the animal table:

$count = $dbh->exec ("INSERT INTO animal (name, category) VALUES (snake, reptile), (frog, amphibian), (tuna, fish), (racoon, mammal)"); exec() returns a count to indicate how many rows were affected by the statement. For the preceding INSERT statement, the affected-rows count is 4.

Issuing Statements That Return a Result Set


Now that the table exists and contains a few records, SELECT can be used to retrieve rows from it. To issue statements that return a result set, use the database handle query() method:

$sth = $dbh->query ("SELECT name, category FROM animal"); printf ("Number of columns in result set: %d\n", $sth->columnCount ()); $count = 0; while ($row = $sth->fetch ()) { printf ("Name: %s, Category: %s\n", $row[0], $row[1]); $count++; } 34

printf ("Number of rows in result set: %d\n", $count);

A successful query() call returns a PDOStatement statement-handle object that is used for all operations on the result set. Some of the information available from a PDOStatement object includes the row contents and the number of columns in the result set: The fetch() method returns each row in succession, or FALSE when there are no more rows. The columnCount() methods returns the number of columns in the result set. Note: A statement handle also has a rowCount() method, but it cannot be assumed to reliably return the number of rows in the result set. Instead, fetch the rows and count them, as shown in the preceding example.

Other Ways To Fetch Result Set Rows


fetch() accepts an optional fetch-mode argument indicating what type of value to return. This section describes some common mode values. Assume in each case that the following query has just been issued to produce a result set:

$sth = $dbh->query ("SELECT name, category FROM animal"); PDO::FETCH_NUM Return each row of the result set as an array containing elements that correspond to the columns named in the SELECT statement and that are accessed by numeric indices beginning at 0: while ($row = $sth->fetch (PDO::FETCH_NUM)) printf ("Name: %s, Category: %s\n", $row[0], $row[1]); PDO::FETCH_ASSOC Return each row as an array containing elements that are accessed by column name: while ($row = $sth->fetch (PDO::FETCH_ASSOC)) printf ("Name: %s, Category: %s\n", $row["name"], $row["category"]);

35

PDO::FETCH_BOTH Return each row as an array containing elements that can be accessed either by numeric index or by column name: while ($row = $sth->fetch (PDO::FETCH_BOTH)) { printf ("Name: %s, Category: %s\n", $row[0], $row[1]); printf ("Name: %s, Category: %s\n", $row["name"], $row["category"]); } PDO::FETCH_OBJ Return each row as an object. In this case, you access column values as object properties that have the same names as columns in the result set:

while ($row = $sth->fetch (PDO::FETCH_OBJ)) printf ("Name: %s, Category: %s\n", $row->name, $row->category);

If you invoke fetch() with no argument, the default fetch mode is PDO::FETCH_BOTH unless you change the default before fetching the rows: The query() method accepts an optional fetch-mode argument following the statement string:

$sth = $dbh->query ("SELECT name, category FROM animal", PDO::FETCH_OBJ); while ($row = $sth->fetch ()) printf ("Name: %s, Category: %s\n", $row->name, $row->category); Statement handles have a setFetchMode() method to set the mode for subsequent fetch() calls: $sth->setFetchMode (PDO::FETCH_OBJ); while ($row = $sth->fetch ()) printf ("Name: %s, Category: %s\n", $row->name, $row->category);

Another way to fetch results is to bind variables to the result set columns with bindColumn(). Then you fetch each row using the PDO::FETCH_BOUND fetch mode. PDO stores the column 36

values in the variables, and fetch() returns TRUE instead of a row value while rows remain in the result set:

$sth = $dbh->query ("SELECT name, category FROM animal"); $sth->bindColumn (1, $name); $sth->bindColumn (2, $category); while ($sth->fetch (PDO::FETCH_BOUND)) printf ("Name: %s, Category: %s\n", $name, $category);

Using Prepared Statements


exec() and query() are PDO object methods: You use them with a database handle and they execute a statement immediately and return its result. It is also possible to prepare a statement for execution without executing it immediately. The prepare() method takes an SQL statement as its argument and returns a PDOStatement statement-handle object. The statement handle has an execute() method that executes the statement:

$sth = $dbh->prepare ($stmt); $sth->execute (); Following execution, other statement-handle methods provide information about the statement result: For a statement that modifies rows, invoke rowCount() to get the rows-affected count: $sth = $dbh->prepare ("DELETE FROM animal WHERE category = mammal"); $sth->execute (); printf ("Number of rows affected: %d\n", $sth->rowCount ()); For a statement that produces a result set, the fetch() method retrieves them and the columnCount() method indicates how many columns there are. To determine how many rows there are, count them as you fetch them. (As mentioned previously, rowCount() returns a row count, but should be used only for statements that modify rows.)

37

$sth = $dbh->prepare ("SELECT name, category FROM animal"); $sth->execute (); printf ("Number of columns in result set: %d\n", $sth->columnCount ()); $count = 0; while ($row = $sth->fetch ()) { printf ("Name: %s, Category: %s\n", $row[0], $row[1]); $count++; } printf ("Number of rows in result set: %d\n", $count);

If you are not sure whether a given SQL statement modifies or returns nows, the statement handle itself enables you to determine the proper mode of processing. See Determining the Type of a Statement. As just shown, prepared statements appear to offer no advantage over exec() and query() because using them introduces an extra step into statement processing. But there are indeed some benefits to them: Prepared statements can be parameterized with placeholders that indicate where data values should appear. You can bind specific values to these placeholders and PDO takes care of any quoting or escaping issues for values that contain special characters. Placeholders and Quoting discusses these topics further. Separating statement preparation from execution can be more efficient for statements to be executed multiple times because the preparation phase need be done only once. For example, if you need to insert a bunch of rows, you can prepare an INSERT statement once and then execute it repeatedly, binding successive row values to it for each execution.

38

Placeholders and Quoting


A prepared statement can contain placeholders to indicate where data values should appear. After you prepare the statement, bind specific values to the placeholders (either before or at statementexecution time), and PDO substitutes the values into the statement before sending it to the database server. PDO supports named and positional placeholders: Anamed placeholder consists of a name preceded by a colon. After you prepare the statement, use bindValue() to provide a value for each placeholder, and then execute the statement. To insert another row, bind new values to the placeholders and invoke execute() again:

$sth = $dbh->prepare ("INSERT INTO animal (name, category) VALUES (:name, :cat)"); $sth->bindValue (":name", "ant"); $sth->bindValue (":cat", "insect"); $sth->execute (); $sth->bindValue (":name", "snail"); $sth->bindValue (":cat", "gastropod"); $sth->execute ();

As an alternative to binding the data values before calling execute(), you can pass the values directly to execute() using an array that associates placeholder names with the values: $sth->execute (array (":name" => "black widow", ":cat" => "spider")); Positional placeholders are characters within the statement string. You can bind the values prior to calling execute(), similar to the previous example, or pass an array of values directly to execute():

$sth = $dbh->prepare ("INSERT INTO animal (name, category) VALUES (?, ?)"); # use bindValue() to bind data values $sth->bindValue (1, "ant"); 39

$sth->bindValue (2, "insect"); $sth->execute (); # pass values directly to execute() as an array $sth->execute (array ("snail", "gastropod"));

Positional placeholder numbers begin with 1.

An alternative to bindValue() is bindParam(), which adds a level of indirection to value-binding. Instead of passing a data value as the second argument to bindParam(), pass a variable to associate the variable with the placeholder. To supply a value for the placeholder, assign a value to the variable:

$sth = $dbh->prepare ("INSERT INTO animal (name, category) VALUES (?, ?)"); $sth->bindParam (1, $name); $sth->bindParam (2, $category); $name = "ant"; $category = "insect"; $sth->execute (); $name = "snail"; $category = "gastropod"; $sth->execute ();

The preceding examples use INSERT statements, but placeholder techniques are applicable to any type of statement, such as UPDATE or SELECT. One of the benefits of using placeholders is that PDO handles any quoting or escaping of special characters or NULL values. For example, if you bind the string "abc" to a placeholder, PDO inserts "a\b\c" into the statement. To bind the SQL NULL value to a placeholder, bind the PHP NULL value. In this case, PDO inserts the word NULL into the statement without surrounding quotes. (Were quotes to be added, the value inserted into the statement would be the string "NULL", which is incorrect.) 40

PDO also provides a database handle quote() method to which you can pass a string and receive back a quoted string with special characters escaped. However, I find this method deficient. For example, if you pass it NULL, it returns an empty string, which if inserted into a statement string does not correspond to the SQL NULL value. Use quote() with care if you use it.

Determining the Type of a Statement


When you issue a statement using a database handle, you must know whether the statement modifies rows or produces a result set, so that you can invoke whichever of exec() or query() is appropriate. However, under certain circumstances, you might not know the statement type, such as when you write a script to execute arbitrary statements that it reads from a file. To handle such cases, use prepare() with the database handle to get a statement handle and execute() to execute the statement. Then check the statements column count: If columnCount() is zero, the statement did not produce a result set. Instead, it modified rows and you can invoke rowCount() to determine the number of affected rows. If columnCount() is greater than zero, the statement produced a result set and you can fetch the rows. To determine how many rows there are, count them as you fetch them. The following example determines whether a statement modifies rows or produces a result set, and then processes it accordingly:

$sth = $dbh->prepare ($stmt); $sth->execute (); if ($sth->columnCount () == 0) { # there is no result set, so the statement modifies rows printf ("Number of rows affected: %d\n", $sth->rowCount ()); } else { # there is a result set printf ("Number of columns in result set: %d\n", $sth->columnCount ()); $count = 0; 41

while ($row = $sth->fetch (PDO::FETCH_NUM)) { # display column values separated by commas print (join (", ", $row) . "\n"); $count++; } printf ("Number of rows in result set: %d\n", $count); }

Handling Errors
When you invoke new PDO() to create a database handle, occurrance of an error causes a PDOException to be thrown. If you dont catch the exception, PHP terminates your script. To handle the exception yourself, use a try block to perform the connection attempt and a catch block to catch any error that occurs:

try { $dbh = new PDO("mysql:host=localhost;dbname=test", "testuser", "testpass"); } catch (PDOException $e) { print ("Could not connect to server.\n"); print ("getMessage(): " . $e->getMessage () . "\n"); }

A PDOException is an extension of the PHP Exception class, so it has getCode() and getMessage() methods that return an error code and descriptive message, respectively. (However, I find that getCode() always returns 0 for connection errors and is meaningful only for PDO exceptions that occur after the connection has been established.) After you successfully obtain a database handle, further PDO calls that use it are handled according to the PDO error mode. There are three modes: 42

PDO::ERRMODE_SILENT When an error occurs in silent or warning mode for a given object method, PDO sets up error information that you can access when the method returns. This is the default error mode. PDO::ERRMODE_WARNING This is like silent mode but PDO also displays a warning message in addition to setting up error information when an error occurs. PDO::ERRMODE_EXCEPTION PDO sets up error information when an error occurs and throws a PDOException. PDO sets error information for the object to which the error applies, regardless of the error mode. This information is available via the objects errorCode() and errorInfo() methods. errorCode() returns an SQLSTATE value (a five-character string). errorInfo() returns a three-element array containing the SQLSTATE value, and a driver-specific error code and error message. For MySQL, the driverspecific values are a numeric error code and a descriptive error message. To handle errors in silent mode, you must check the result of each PDO call. The following example shows how to test for errors during an operation that uses a database handle, $dbh, and a statement handle, $sth (you would not necessarily print all the available information as the example does):

if (!($sth = $dbh->prepare ("INSERT INTO no_such_table"))) { print ("Could not prepare statement.\n"); print ("errorCode: " . $dbh->errorCode () . "\n"); print ("errorInfo: " . join (", ", $dbh->errorInfo ()) . "\n"); } else if (!$sth->execute ()) { print ("Could not execute statement.\n"); print ("errorCode: " . $sth->errorCode () . "\n"); print ("errorInfo: " . join (", ", $sth->errorInfo ()) . "\n"); } Testing the result of every call can become messy quickly. Another way to deal with failures is 43

to set the error handling mode so that any error raises an exception:

$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); In this case, you can assume that if you invoke a method and it returns, it succeeded. You can either leave exceptions uncaught or catch and handle them yourself. If you leave them uncaught, exceptions cause PHP to print a backtrace and terminate your script. To catch exceptions, perform PDO operations using a try/catch construct. The try block contains the operations and the catch block handles an execption if one occurs.

try { $sth = $dbh->prepare ("INSERT INTO no_such_table"); $sth->execute (); } catch (PDOException $e) { print ("The statement failed.\n"); print ("getCode: ". $e->getCode () . "\n"); print ("getMessage: ". $e->getMessage () . "\n"); } By using try and catch, you can substitute your own error messages if you like, perform cleanup operations, and so on. As shown in the preceding example, the try block can contain operations on multiple handles. However, if an exception occurs in that case, you wont be able to use the handle-specific errorCode() or errorInfo() methods in the catch block very easily because you wont know which handle caused the error. Youll need to use the information available from the exception methods, as shown.

44

Using Transactions
In MySQL, some storage engines are transactional, which enables you to perform an operation and then commit it permanently if it succeeded or roll it back to cancel its effects if an error occurred. PDO provides a mechanism for performing transactions that is based on the following database-handle methods: To start a transaction, invoke beginTransaction() to disable autocommit mode so that database changes do not take effect immediately. To commit a successful transaction or roll back an unsuccessful one, invoke commit() or rollback(), respectively. The easiest way to use these methods is to enable PDO exceptions and use try and catch to handle errors:

$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $dbh->beginTransaction (); # start the transaction # ... perform database operation ... $dbh->commit (); # success } catch (PDOException $e) { print ("Transaction failed: " . $e->getMessage () . "\n"); $dbh->rollback (); # failure } For additional paranoia, you can place the rollback() call within a nested try/catch construct so that if rollback() itself fails and raises another exception, the script doesnt get terminated. http://www.

45

14. STRUCTURED QUERY LANGUAGE SQL is a set of commands that all programmers and users must use to access data with inORACLE database. The Oracle 8i server provides full SQL commands to level 2 and fullimplementation of the integrity enhancement features. The SQL consists of facilities for defining accessing and managing relational database. Advantages of SQL: 1. SQL has become a database language of choice because it is flexible, powerfuland easy to learn. 2. SQL is non procedural language it o Process sets of records rather than just one at a time. o Provides automatic navigation to the data. 3. SQL Provides commands for a variety of tasks including querying data, creating,updating and replacing objects and inserting, updating and deleting rows. 4. All major RDBMS supports SQL. Thus one can transfer all the skills gained withSQL from one RDBMS to another. 5. Programs written in SQL are portable; they can often be moved from onedatabase system to another with little modification.

SQL Commands
The SQL Commands are divided into three categories:

Data Definition Language Commands (DDL) Data Manipulation Language Commands (DML) Transaction Control Commands.

46

TYPES OF SQL OPERATORS


Query data. Updating. Inserting and Deleting database Objects. Controlling access to the database. Providing for data integrity and consistency.

47

15. Database Tables:

1. Booking_info

Bookingid Int(5)NOT NULL

Userid Varchar(50) NOT NULL

Showid Int(5) NOT NULL

Bookeddate bookedseat DATE NOT NULL Varchar(4) NOT NULL

2. Movies

movi eid Int(5) NOT ULL

Movie name Varch ar(50) NOT NULL L

Tagline Dateofrel ease

Synopsi s

Posterid

Running_ti me_in_min

Language

cbfcrati ng

Added_ by Varchar( 50) DEFAU LT NULL

Varchar Date NOT Long (50) DEFA ULT NULL NULL text

Varchar(50 ) DEFAULT NULL

Int(11) DEFAULT 90

NOT NULL DEFAULT ENGLISH

NOT NULL DEFAU LT U

3. States

Stateid Int(3) unsigned NOT NULL

State Varchar(40) NOT NULL

48

4. State_city

Cityid
Int(10) unsigned NOT NULL

Stateid
Int(3) NULL unsigned

State
NOT Varchar(40) NULL DEFAULT

5. Theaters

theatre id
Int(5) Unsigne

Theatre name
Varchar (30)

Addres s1
Varchar (50) NOT NULL

Addres s2
Varchar (50) DEFAU LT NOT NULL

Area

City

State

Country

Screens

Added_by

Varchar(30) NOT NULL

Varchar(30) NOT NULL

Varchar(30) NOT NULL

Varchar(3 0) NOT NULL DEFAUL T INDIA

Varchar(1 0) UNSIGN

Varchar(50) DEFAULT NULL WHO ADDED IT

d NOT NOT NULL NULL

ED NOT COMMENT NULL DEFAUL T 1

6. Users

Useri d

Emailid

Passwo rd

First_n ame

Middle _name

Last_n ame

Phone _num ber

State

City

Doj

Activate d_user

Change_ pass_ on_ login

Int(5) Varchar( 50)

Varcha r(40)

Varcha r(50)

Varcha r(50)

Varcha r(50)

Varch ar(13)

Varcha r(2)

Varcha r(3)

TIMESTAMP NOT DERAULF CURRENT_TIM ESTAMP

Binary(

Binary(1)

NULL 1) NOT NOT NULL NULL DEFAU LT 0 DEFAULT 1

49

16. Usecase

Diagrams:
Usecase Diagram 1
Check by movie <<extends>>

Registration

< Check movie data Unregistered user

<<extends>>

Chek by cinema hall

<<extends>>

Check by time

Usecase Diagram 2
Request ticket

<<includes>>

<<includes>> Login <<includes>> Book ticket

<<includes Registered user >>


Check status of ticket

50

Usecase Diagram 3

Register new administrator <<includes>>

<<includes>> Administrator login <<includes>>

Create movie database

Administrator <<includes>>

Update movie database

<<includes>> Approve user request

51

17.

DATA FLOW DIAGRAM:

A data flow diagram is graphical tool used to describe and analyze movement of data through a system. These are the central tool and the basis from which the other components are developed. The transformation of data from input to output, through processed, may be described logically and independently of physical components associated with the system. These are known as the logical data flow diagrams. The physical data flow diagrams show the actual implements and movement of data between people, departments and workstations. A full description of a system actually consists of a set of data flow diagrams. Using two familiar notations Yourdon, Gane and Sarson notation develops the data flow diagrams. Each component in a DFD is labeled with a descriptive name. Process is further identified with a number that will be used for identification purpose. The development of DFDs is done in several levels. Each process in lower level diagrams can be broken down into a more detailed DFD in the next level. The toplevel diagram is often called context diagram. It consists a single process bit, which plays vital role in studying the current system. The process in the context level diagram is exploded into other process at the first level DFD.

The idea behind the explosion of a process into more process is that understanding at one level of detail is exploded into greater detail at the next level. This is done until further explosion is necessary and an adequate amount of detail is described for analyst to understand the process.

Larry Constantine first developed the DFD as a way of expressing system requirements in a graphical from, this lead to the modular design. A DFD is also known as a bubble Chart has the purpose of clarifying system requirements and identifying major transformations that will become programs in system design. So it is the starting point of the design to the lowest level of detail. A DFD consists of a series of bubbles joined by data flows in the system.

52

DFD SYMBOLS:
In the DFD, there are four symbols

1. A square defines a source(originator) or destination of system data 2. An arrow identifies data flow. It is the pipeline through which the information flows 3. A circle or a bubble represents a process that transforms incoming data flow into outgoing data flows. 4. An open rectangle is a data store, data at rest or a temporary repository of data

Process that transforms data flow

External entity External Entity

Data flow

Data Store

Output

53

Salient Features of DFDs


1. The DFD shows flow of data, not of control loops and decision are controlled considerations do not appear on a DFD. 2. The DFD does not indicate the time factor involved in any process whether the dataflow take place daily, weekly, monthly or yearly. 3. The sequence of events is not brought out on the DFD.

Types of Data Flow Diagrams


1. Current Physical 2. Current Logical 3. New Logical 4. New Physical

DATA FLOW
1) A Data Flow has only one direction of flow between symbols. It may flow in both directions between a process and a data store to show a read before an update. The later is usually indicated however by two separate arrows since these happen at different type. 2) A join in DFD means that exactly the same data comes from any of two or more different processes data store or sink to a common location. 3) A data flow cannot go directly back to the same process it leads. There must be at least one other process that handles the data flow produce some other data flow returns the original data into the beginning process. 4) A Data flow to a data store means update (delete or change). 5) A data Flow from a data store means retrieve or use. 6) A data flow has a noun phrase label more than one data flow noun phrase can appear on a single arrow as long as all of the flows on the same arrow move together as one package.

54

Context Diagram

Send Output

ADMINISTRATOR
Admin id and Password

Admin views user details,movie/cinema hall

UNREGISTERED USER
No Identity Required

www.movie.jagzlabs.com
Get cinema ticket(s)

Send Output

User id and Password

REGISTERED USER

Send Output

View movie/cinema hall details

55

Level 1 Dataflow Diagram


Assign movie details 1.1

Movie details

Administrator

Assign movie details 1.2

Movie details

Cinema hall details 1 .3

Cinema hall details

Modifying show details 1.4 Cinema hall details

56

Level 2 Dataflow Diagram

Cinema show time details

Select movie select status 2.1.1

Cinema show time details

User

Login 2.1 Select date select show 2.1.2 Booked details

User details Movie details Movie status

57

18. Entity

Relationship Diagram

58

19. Online Cinema Ticket Booking Description

Welcome to newly designed website cinema ticket booking is a faster, cleanerand a tad more personal website, specially designed to make your bookingexperience better. Log on, navigate and find out for yourselves and if time permits leave your valuable feedback.Customers may view the contents of any movie show at any time and may bookany movie ticket as needed. The program automatically calculates the subtotal and grand total. When a visitor decides to finally book the ticket, the order information including the buyer's name, address and billing instruction is storedin the database securely and payment has been made. You need to register a new user whenever you have first visited or site then forfuture it will be stored in our database permanently and you can book you movieticket at any time you want with this username and password.

Online Cinema Ticket BookingFeatures:


Database Search Feature Supports credit card transactions Supports SQL database for movie database for speedy movie info lookups. Can save customer contact information for their next visit, so they do nothave to re-type it. Using the SQL module the cart can handle very large product databases. Ability to store order information in a secure file Ability to assign the different seat numbers to different users.

59

Online Cinema Ticket Booking Working


The booking information is kept in a text database, which consists of: booking id,user id,show id,book date and book seat. This database is modified when the userbooks the ticket.The customer can be presented with a booking page upon logging in, which allows them to search for the desired movies available on the desired date and book for a desired show. The bookingpage also shows the seat type to be booked, no of seats to be booked, servicecharges to be applied, ticketing cost and net payable amount to the customer.When the customers have done their booking they will checkout using the payment information page. This page collects data about the customer, his bankname, his credit card number, credit card type, address, telephone number,mobile number, and CVV information.

60

20. Screenshots :

Home Screen:

61

New User Registration Screen:

62

Login Screen:

63

21. CODING: Registration for new user: <?php require_once ($_SERVER['DOCUMENT_ROOT'].'/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/conf/dbreguser.inc.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteUsers.class.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' ); $generatedPassword = generatePassword(9, 4) ; $userObj->setFirstName(sanitizeNames($_POST['fName'])); $userObj->setMiddleName(sanitizeNames($_POST['mName'])); $userObj->setLastName(sanitizeNames($_POST['lName'])); $userObj->setEmailId(sanitizeEmail($_POST['email'])); $userObj->setPhoneNumber(sanitizeNumber($_POST['phone'])); $userObj->setCity(sanitizeNames($_POST['city'])); $userObj->setState(sanitizeNames($_POST['state'])); $userObj->setPassword(sha1($generatedPassword)); $userObj->setActivatedUser(0); $userObj->setChangePassOnLogIn(1); $userObj->setRoleId(1); echo '<div class="message">'; try { $result = $userObj->insertIntoDatabase($conn); if ($result){ echo SUCCESS ; echo '<p>You are successfully registered on '.SITE_NAME.'. Please check your email-id '.$_POST['email'].' for password. Please use the password <span class="password">'.$generatedPassword.'</span> to login.</p>'; } else { echo FAILURE ; echo '<p>There seems to be a problem with '.SITE_NAME.'. Please try again later.</p>'; } } catch (PDOException $e) { $result = $e->getCode() ; switch ($result){ case 1062 : echo '<p>It seems like you are already registered on '.SITE_NAME.' with '.$_POST['email'].'. Would you like to reset your password ?</p>'; } } echo '</div>'; ?> 64

Login for Existing User: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteUsers.class.php'); require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteSessions.class.php'); $emailid = sanitizeEmail($_POST['emailAddress']); $upass = stripslashes($_POST['password']); $userObj = new SiteUsers(); $sessionsObj = new SiteSessions(); $userObj->setEmailId($emailid); $userObj->setPassword(sha1($upass)); $userObj = SiteUsers::findByExample($conn, $userObj) ; if (count($userObj)) { session_set_cookie_params(time() + 3600, "/"); session_destroy(); session_start(); $changePass = 0; foreach ($userObj as $userDetails) { $_SESSION['userrole'] = $userDetails->getRoleId(); $_SESSION['name'] = $userDetails->getFirstName(); $changePass = $userDetails->getChangePassOnLogin(); $logInDate = date('Y-m-d H:i:s'); $expInterval = strtotime('+1 hour'); $expTime = date('Y-m-d H:i:s', $expInterval); $sessiondata = session_id(); $sessionsObj->setSessionData($sessiondata); $sessionsObj->setEmailId($emailid); if (!count(SiteSessions::findByExample($conn, $sessionsObj))) { $sessionsObj->setLoggedIn($logInDate); $sessionsObj->setExpires($expTime); $sessionsObj->insertIntoDatabase($conn); } else { $sessionsObj->setLoggedIn($logInDate); $sessionsObj->setExpires($expTime); $sessionsObj->updateToDatabase($conn); } } $_SESSION['emailid'] = $userDetails->getEmailId(); 65

if (!((int)$changePass)) { echo "validuser"; } else { echo "changePass"; } } else { session_destroy(); echo "invaliduser"; } ?>

66

Change password: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteUsers.class.php'); require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteSessions.class.php'); $emailid = sanitizeEmail($_POST['emailAddress']); $newPass = stripslashes($_POST['newPass']); $oldPass = stripslashes($_POST['curPass']); $userObj = new SiteUsers(); $sessionsObj = new SiteSessions(); $userObj->setEmailId($emailid); $userObj->setPassword(sha1($oldPass)); $matched = SiteUsers::findByExample($conn, $userObj); if (count($matched)) { session_set_cookie_params(time() + 3600, "/"); session_destroy(); session_start(); foreach ($matched as $matchedUser) { $matchedUser->setPassword(sha1($newPass)); $matchedUser->setActivatedUser(1); $matchedUser->setChangePassOnLogIn(0); $result = $matchedUser->updateToDatabase($conn); if ($result) { echo "success"; } else { echo "There seems to be a password mismatch. Please refresh to try again."; } } } else { session_destroy(); echo "invaliduser"; } ?>

67

Log Out: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteUsers.class.php'); require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteSessions.class.php'); $sessionData = session_id(); $sessionsObj = new SiteSessions(); $sessionsObj->setSessionData($sessionData); $sessionsObj->deleteFromDatabase($conn); session_unset(); unset($_SESSION); session_destroy(); header('Location: /index.php'); ?>

68

Administrator Functions:
Save Movies: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' ); require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteMovies.class.php'); $emailid = $_SESSION['emailid']; $roleid = $_SESSION['userrole']; if (checkValidSessionAndRoleForEmailId($conn, $emailid, $roleid) && $roleid = 3) { $movieObj = new SiteMovies(); $postData = $_POST ; $movieObj->assignByHash($postData) ; $movieObj->setDateOfRelease($date = date('Y-m-d', strtotime(str_replace('-', '/', $date)))); if (isset($_POST['movieid'])) { $id=$_POST['movieid'] ; $result = SiteMovies::getDetailsForMovieId($conn, $id); if (count($result) > 0) { $upd = $movieObj->updateToDatabase($conn); if ($upd) { echo "<h4 class='success msg'>Movie Description Updated</h4>"; } else { echo "<h4 class='failure msg'>Unable to Update. Please try later.</h4>"; } } else { invalidateSession(); } } else { $ins = $movieObj->insertIntoDatabase($conn); if ($ins) { echo "<h4 class='success msg'>Screen Description Saved</h4>"; } else { echo "<h4 class='failure msg'>Unable to Save. Please try later.</h4>"; } } } else { invalidateSession(); } ?> 69

Save Screen Type: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' ); require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteScreenTypes.class.php'); $emailid = $_SESSION['emailid']; $roleid = $_SESSION['userrole']; if (checkValidSessionAndRoleForEmailId($conn, $emailid, $roleid) && $roleid = 3) { $screenTypeObj = new SiteScreenTypes(); if (isset($_POST['screenId'])) { $screenTypeObj->setScreenId($_POST['screenId']); } else { $screenTypeObj->setAddedBy($emailid); $screenTypeObj->setScreenType(sanitizeNames($_POST['screenTypeName'])); $screenTypeObj->setDescription(stripslashes($_POST['screenDesc'])); } $result = SiteScreenTypes::findByExample($conn, $screenTypeObj); if (count($result) > 0) { $screenTypeObj->setAddedBy($emailid); $screenTypeObj->setScreenType(sanitizeNames($_POST['screenTypeName'])); $screenTypeObj->setDescription(stripslashes($_POST['screenDesc'])); $upd = $screenTypeObj->updateToDatabase($conn); if ($upd) { echo "<h4 class='success msg'>Screen Description Updated</h4>"; } else { echo "<h4 class='failure msg'>Unable to Update. Please try later.</h4>"; } } else { $ins = $screenTypeObj->insertIntoDatabase($conn); if ($ins) { echo "<h4 class='success msg'>Screen Description Saved</h4>"; } else { echo "<h4 class='failure msg'>Unable to Save. Please try later.</h4>"; } } } ?>

70

Manager Functions:
Save Screen: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] '/core/classes/SiteTheaterScreens.class.php'); $added_by = $_SESSION['emailid']; $roleid = $_SESSION['userrole']; if (checkValidSessionAndRoleForEmailId($conn, $emailid, $roleid) && $roleid = 2) { $screenObj = new SiteTheaterScreens(); if (isset($_POST['screenid'])) { $id = sanitizeNumber($_POST['screenid']); $screenObj->setTheatreScreenId($id); $result = SiteTheaterScreens::getScreenByScreenId($conn, $id); if (count($result) > 0) { $screenObj->setAddedBy(sanitizeEmail($added_by)); $screenObj->setScreenName(sanitizeNames($_POST['screenName'])); $screenObj->setTheatreId(sanitizeNumber($_POST['selectTheater'])); $screenObj->setScreenType(sanitizeNumber(sanitizeNumber($_POST['screenType']))); $screenObj->setCapacity(sanitizeNumber($_POST['capacity'])); $screenObj->setCostPerSeat(sanitizeNumber($_POST['seatcost'])); $upd = $screenObj->updateToDatabase($conn); if ($upd) { echo "<h4 class='success msg'>Screen Updated</h4>"; } else { echo "<h4 class='failure msg'>Unable to Update. Please try later.</h4>"; } } } else { $screenObj->setAddedBy(sanitizeEmail($added_by)); $screenObj->setScreenName(sanitizeNames($_POST['screenName'])); $screenObj->setTheatreId(sanitizeNumber($_POST['selectTheater'])); $screenObj->setScreenType(sanitizeNumber(sanitizeNumber($_POST['screenType']))); $screenObj->setCapacity(sanitizeNumber($_POST['capacity'])); $screenObj->setCostPerSeat(sanitizeNumber($_POST['seatcost'])); $ins = $screenObj->insertIntoDatabase($conn); if ($ins) { echo "<h4 class='success msg'>Screen Saved</h4>"; 71

} else { echo "<h4 class='failure msg'>Unable to Save. Please try later.</h4>"; } } } else { invalidateSession(); } ?>

72

Save Seats:
<?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' );

$added_by = $_SESSION['emailid']; $roleid = $_SESSION['userrole']; if (checkValidSessionAndRoleForEmailId($conn, $emailid, $roleid) && $roleid = 2) { $seatObj = new SiteTheaterScreenSeats(); if (isset($_POST['screenid'])) { $id= sanitizeNumber($_POST['screenid']); $seatObj->setTheatersCReEnid($id) ; $seatObj->setRowId(sanitizeNames($_POST['rowid'])); $results = SiteTheaterScreenSeats::findByExample($conn, $seatObj) ; if (count($results) > 0){ $seatObj->setRowSeats(sanitizeNumber($_POST['rowseats'])); $seatObj->setAddedBy(sanitizeEmail($added_by)); $seatObj->updateToDatabase($conn); } else { $seatObj->setRowSeats(sanitizeNumber($_POST['rowseats'])); $seatObj->setAddedBy(sanitizeEmail($added_by)); $seatObj->insertIntoDatabase($conn); } } else { invalidateSession(); } } else { invalidateSession(); } ?>

73

Save Show:
<?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' );

$emailid = $_SESSION['emailid']; $roleid = $_SESSION['userrole']; if (checkValidSessionAndRoleForEmailId($conn, $emailid, $roleid) && $roleid = 2) { $showObj = new SiteScreenShowTimes() ; if (isset($_POST['showid'])) { $id = sanitizeNumber($_POST['showid']); $showObj->setTheatreScreenId($id); $result = SiteTheaterScreens::getScreenByScreenId($conn, $id); if (count($result) > 0) { $upd = $screenObj->updateToDatabase($conn); if ($upd) { echo "<h4 class='success msg'>Screen Updated</h4>"; } else { echo "<h4 class='failure msg'>Unable to Update. Please try later.</h4>"; } } } else { $showObj->setMovieId(sanitizeNumber($_POST['moviename'])) ; $showObj->setAddedBy(sanitizeEmail($_POST['added_by'])) ; $showObj->setShowtime($_POST['time']); $showObj->setTheaterScreenId($_POST['screenid']); $ins = $showObj->insertIntoDatabase($conn); if ($ins) { echo "<h4 class='success msg'>Screen Saved</h4>"; } else { echo "<h4 class='failure msg'>Unable to Save. Please try later.</h4>"; } } } else { invalidateSession(); } ?>

74

Save Theatre: <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/core/def.core.php'); require_once($_SERVER['DOCUMENT_ROOT'] . "/core/conf/dbreguser.inc.php"); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/sanitize.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/helpers.core.php' ); require_once($_SERVER['DOCUMENT_ROOT'] . '/core/classes/SiteTheaters.class.php'); $added_by = $_SESSION['emailid']; $roleid = $_SESSION['userrole']; if (checkValidSessionAndRoleForEmailId($conn, $emailid, $roleid) && $roleid = 2) { $theaterObj = new SiteTheaters(); if (isset($_POST['theaterid'])) { $id = sanitizeNumber($_POST['theaterid']); $result = SiteTheaters::getTheaterByTheaterId($conn, $id); if (count($result)) { $theaterObj->setTheaterId($id); $theaterObj->setTheaterName(sanitizeNames($_POST['theaterName'])); $theaterObj->setAddress1(sanitizeAddress($_POST['addLine1'])); if (isset($_POST['addLine2'])) { $theaterObj->setAddress2(sanitizeAddress($_POST['addLine2'])); } $theaterObj->setArea(sanitizeAddress($_POST['area'])); $theaterObj->setCity(sanitizeNumber($_POST['city'])); $theaterObj->setState(sanitizeNumber($_POST['state'])); $theaterObj->setCountry('India'); $theaterObj->setScreens(sanitizeNumber($_POST['numScreens'])); $theaterObj->setAddedBy(sanitizeEmail($added_by)); $upd = $theaterObj->updateToDatabase($conn); if ($upd) { echo "<h4 class='success msg'>Theater Updated</h4>"; } else { echo "<h4 class='failure msg'>Unable to Update. Please try later.</h4>"; } } else { invalidateSession(); } } else { $theaterObj->setTheaterName(sanitizeNames($_POST['theaterName'])); $theaterObj->setAddress1(sanitizeAddress($_POST['addLine1'])); if (isset($_POST['addLine2'])) { 75

$theaterObj->setAddress2(sanitizeAddress($_POST['addLine2'])); } $theaterObj->setArea(sanitizeAddress($_POST['area'])); $theaterObj->setCity(sanitizeNumber($_POST['city'])); $theaterObj->setState(sanitizeNumber($_POST['state'])); $theaterObj->setCountry('India'); $theaterObj->setScreens(sanitizeNumber($_POST['numScreens'])); $theaterObj->setAddedBy(sanitizeEmail($added_by)); $ins = $theaterObj->insertIntoDatabase($conn); if ($ins) { echo "<h4 class='success msg'>Theater Saved</h4>"; } else { echo "<h4 class='failure msg'>Unable to Save. Please try later.</h4>"; } } } else { invalidateSession(); } ?>

76

22. Testing Testing is the process of detecting errors. Testing performs a very critical role for quality assurance and for ensuring the reliability of software. The results of testing are used later on during maintenance also.

Testing Objectives
The main objective of testing is to uncover a host of errors, systematically and with minimum effort and time. Stating formally, we can say,

Testing is a process of executing a program with the intent of finding an error. A successful test is one that uncovers an as yet undiscovered error. A good test case is one that has a high probability of finding error, if it exists. The tests are inadequate to detect possibly present errors. The software more or less confirms to the quality and reliable standards.

Levels of Testing
In order to uncover the errors present in different phases we have the concept of levels of testing. The basic levels of testing are as shown below.

1. SystemTesting
The philosophy behind testing is to find errors. Test cases are devised with this in mind. A strategy employed for system testing is code testing.

2. CodeTesting:
This strategy examines the logic of the program. To follow this method we developed some test data that resulted in executing every instruction in the program and module i.e. every path is tested. Systems are not designed as entire nor are they tested as single systems. To ensure that the coding is perfect two types of testing is performed or for that matter is performed or that matter is performed or for that matter is performed on all systems.

77

Levels of Testing
Unit Testing Integration Testing
System Testing

Unit Testing
Unit testing focuses verification effort on the smallest unit of software i.e. the module. Using the detailed design and the process specifications testing is done to uncover errors within the boundary of the module. All modules must be successful in the unit test before the start of the integration testing begins.

Integration Testing
After the unit testing we have to perform integration testing. The goal here is to see if modules can be integrated properly, the emphasis being on testing interfaces between modules. This testing activity can be considered as testing the design and hence the emphasis on testing module interactions. In this project integrating all the modules forms the main system. When integrating all the modules I have checked whether the integration effects working of any of the services by giving different combinations of inputs with which the two services run perfectly before Integration.

System Testing
Here the entire software system is tested. The reference document for this process is the requirements document, and the goal os to see if software meets its requirements. Here entire ATM has been tested against requirements of project and it is checked whether all requirements of project have been satisfied or not.

78

Acceptance Testing
Acceptance Test is performed with realistic data of the client to demonstrate that the software is working satisfactorily. Testing here is focused on external behavior of the system; the internal logic of program is not emphasized.

White Box Testing


This is a unit testing method where a unit will be taken at a time and tested thoroughly at a statement level to find the maximum possible errors. I tested step wise every piece of code, taking care that every statement in the code is executed at least once. The white box testing is also called Glass Box Testing. I have generated a list of test cases, sample data. which is used to check all possible combinations of execution paths through the code at every module level.

Black Box Testing


This testing method considers a module as a single unit and checks the unit at interface and communication with other modules rather getting into details at statement level. Here the module will be treated as a block box that will take some input and generate output. Output for a given set of input combinations are forwarded to other modules.

79

23. CONCLUSION The project "ONLINETICKET RESERVATION SYSTEM FOR CINEMA HALLS is designed for cinema halls, multiplexes which is auser friendly system, because customers can avoid long queues and saving their precious time. They can collect the ticket at the counter at the time of show. It is a fully automated system which provides a lot of good things to the customers. It will provide user friendly environment and completely flexible.The system can be used with little or no modifications by all the cinema theatres. By using this system the availability of tickets is known well in advance so that customers can plan accordingly. The large crowd can be avoided. The tickets will be provided with the user-id.While some of the limitations of this system is that the user has to be educated to work with this system. Development, implementation and maintenance are comparativelyexpensive.

80

References:
The following books were referred during the analysis and execution phase of the project:

1. MySQL REFERENCE MANUAL By Sun Microsystems 2. SOFTWARE ENGINEERING By Roger.S.Pressman 3. PHP: THE COMPLETE REFERENCE By Steven Holzner 4. The home site for MySQL is: http://www.mysql.com/ 5. The home site for PHP is: http://www.php.net/ 6. Other documents similar to this one are available that show how to access using MySQL using PHPs PEAR DB module or interfaces for other programming languages: http://www.kitebird.com/articles/

81

Вам также может понравиться