PHP OOPS Interview Questions & Answers 1) Explain what is object oriented programming language?

Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance. Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an bject. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming. OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more. 2) Name some languages which have object oriented language andcharacteristics? Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.

3) Explain about UML?

UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.

4) Explain the meaning of object in object oriented programming?

Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.

5) Explain about message passing in object oriented programming? Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing.

It acts like a messenger from one object to other object to convey specific instructions.
6) State about Java and its relation to Object oriented programming?

Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C and C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.

7) What are the problems faced by the developer using object oriented programming language?

These are some of the problems faced by the developer using object oriented language they are: a) Object oriented uses design patterns which can be referred to as anything in general.
b) Repeatable solution to a problem can cause concern and disagreements and it

is one of the major problems in software design.

8 ) State some of the advantages of object oriented programming? Some of the advantages of object oriented programming are as follows: a) A clear modular structure can be obtained which can be used as a prototype and it

will not reveal the mechanism behind the design. It does have a clear interface.

b) Ease of maintenance and modification to the existing objects can be done with

ease.
c) A good framework is provided which facilitates in creating rich GUI applications.

9 ) Explain about inheritance in OOPS?

Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.

10) Explain about the relationship between object oriented programming anddatabases?

Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.

11) Explain about a class in OOP?

In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

12) Explain the usage of encapsulation? Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.

13) Explain about abstraction?

Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.

14) Explain what a method is?

A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.

. It speeds the program development process. 2) Explain about Object oriented programming? Object oriented programming is one of the most popular methodologies in software development. more effectively. The object oriented approach allows you to identify entities as objects having attributes and behavior. improves maintenance and enhances reusability of programs. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages. It offers a powerful model for creating computer programs. 1) Explain the rationale behind Object Oriented concepts? Object oriented concepts form the base of all modern programming languages. 17) Explain about the analysis phase? The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. it logically follows that the object oriented approach models the real world accurately. Critical requirements needs to be identified.15) Name the different Creational patterns in OO design? There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: a) Factory pattern b) Single ton pattern c) Prototype pattern d) Abstract factory pattern e) Builder pattern 16) Explain about realistic modeling? As we live in a world of objects. Developer concentrates on obtaining as much information as possible about the problem.

Class acts like a blue print.3) Explain what is an object? An object is a combination of messages and data. Values defined for a particular object define its State. Instance of a particular object is created at runtime. The messages contain information that is to be passed to the recipient object. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. the developers of the system document their understanding of the system. 6) Explain about a class? Class describes the nature of a particular thing. During the implementation phase. 5) Explain about the Design Phase? In the design phase. which is the implementation phase. Structure and modularity is provided by a Class in object oriented programming environment. Instance of an object explains the relation ship between different elements. 4) Explain the implementation phase with respect to OOP? The design phase is followed by OOP. OOP provides specifications for writing programs in a programming language. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships. 8 ) Explain about inheritance? Inheritance revolves around the concept of inheriting knowledge and class attributes . 7) Explain about instance in object oriented programming? Every class and an object have an instance. Objects can receive and send messages and use messages to interact with each other. programming is done as per the requirements gathered during the analysis and design phases.

It makes different classes and objects to interact with each other thus making the problem to be solved automatically. 13) Explain about polymorphism? Polymorphism helps a sub class to behave like a parent class.from the parent class. Composition also helps in solving the problem to an extent. It simplifies the problem by giving the class its specific class of inheritance. In multiple inheritance a class can have characteristics from multiple parents or classes. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. It interacts with the problem by making different classes and objects to send a message to each other. 11) Explain about abstraction? Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. 9) Explain about multiple inheritance? Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. . It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned. 10) Explain about encapsulation? Encapsulation passes the message without revealing the exact functional details of the class. When an object belonging to different data types respond to methods which have a same name. 12) Explain the mechanism of composition? Composition helps to simplify a complex problem into an easier problem. the only condition being that those methods should perform different function. A sub class can have characteristics from multiple parents and still can have its own characteristics. Inheritance forms an important concept in object oriented programming.

16) Explain about parametric polymorphism? Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. Overriding polymorphism is generally used in complex projects where the use of a parameter is more. etc use OOP. Coldfusion. Ruby. 15) Explain about object oriented databases? Object oriented databases are very popular such as relational database management systems._trackPageview().location. In parametric polymorphism code is written without any specification for the type of data present.14) Explain about overriding polymorphism? Overriding polymorphism is known to occur when a data type can perform different functions. Languages such as Python. Hence it can be used any number of times. These DBMS use object oriented languages to make the process easier._getTracker(”UA-1855756-5?).protocol) try { var pageTracker = _gat. pageTracker. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. For example an addition operator can perform different functions such as addition. } catch(err) {} . 17) What are all the languages which support OOP? There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. float addition etc. PHP. Still many languages prefer to use DOM based languages due to the ease in coding. var gaJsHost = ((”https:” == document. Ruby on rails. Perl.

GET: we are submitting a form to login.)”GET” is basically for just getting (retrieving: quering db for data & retriving) data whereas “POST” may involve anything. 3. PHP 5.php. .php’) and is retrieved by login. when we do ’submit’ orsimilar action to post the form.What are the differences between Get and post methods in form submitting. then you can use “GET”Method. Once most imp diff is when you are sending the form with“Get” method. for e.g. or drop down. You can see the output which you are sendingin the addressbar. When user click on checkbox.. values are sent through ‘invisible’ standeredinput (notice ‘.php by $_GET[’username’] and $_GET[’password’].1. HEAD. when we do ’submit’ or similaraction to post the form values are sent through ‘visible’ query string andis retrieved by login. or ordering a product. For GET in IE. The methods GET. Maximum URL Length Is 2. When user click on radio button. 2 In simple words. (Idompotent: The side-effects of N > 0 identical requests is the same as for a single request. 3. like storing or updating data.php. Beta MySQL 5. At the end of the form I will type “Click here.POST is assumed more secure and we can send lot more data than that of GETmethod is limited(they say Internet Explorer can take care of maximum 2083 characteras a query string). Who is the father of PHP and explain the changes in PHP versions? Ans : Rasmus Lerdorf is the father of PHP.php by $_POST[’username’]and $_POST[’password’]. But for long data sending say more then 100character you can use “POST” method.? ex:Assume we are logging in with username and password. Whereas if you send the form with “POST”method then user can not see that information. How can we submit a form without a submit button? Ans : I can submit a form in many ways.0 4. 1. Get is an Idompotent method. In GET form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. 2. PUT and DELETE share this property.not containing ASCII characters. in POST method data is sent by standered input (nothing shown in url when posting while in GET method data is sent through query string.POST :we are submitting a form to login./login.1.083 Characters in Internet Explorer (Q208427) or approximatly 1k. give the case where we can use get and we can use post methods? Ans : When you want to send short or small data. or sending E-mail.

We can submit a from without a submit button help ho javascript like. For ex: If $message contains “var”. mysql_fetch_row — Get a result row as an enumerated array. mysql_fetch_assoc — Fetch a result row as an associative array.What is the difference between mysql_fetch_object and mysql_fetch_array? mysql_fetch_array — Fetch a result row as an associative ARRAY. or both mysql_fetch_object — Fetch a result row as an OBJECT. In how many ways we can retrieve the date in the result set of mysql using PHP? mysql_fetch_array — Fetch a result row as an associative array. 6. that means that you can onlyaccess the data by the field names.submit(). Speed-wise. a numeric array. instead of an array.an object is returned.an object is returned. a numeric array.myform. the function is identical to mysql_fetch_array(). that means that you can only access the data by the field names. mysql_fetch_object — Fetch a result row as an object. Trigger the JavaScript code on any event ( like onselect of drop down list box. then it displays the content of $var on the screen. with one difference . Indirectly. 7 What is the difference between $message and $$message? Both are variables only$message is a variable and if used with print statement.submit(). . the content of the $message variable will be displayed.instead of an array. etc ) document.This will submit the form.to submit” & link text to the processing file.with one difference . mysql_fetch_object() is similar to mysql_fetch_array(). the content of the $message will also be treated as variable and the content of that variable will be displayed. and not by their offsets(numbers are illegal property names). Where as with $$message variable. <a href=”void(0)” rel=”nofollow”>Submit Me</a> 5.and almost as quick as mysql_fetch_row() (the difference isinsignificant). and not by their offsets (numbers are illegal property names). or both. Indirectly. onfocus. form. mysql_fetch_object() is similar to mysql_fetch_array().

or $exploded[1] should have abc. $link)) { echo “Database my_db created successfully\n”. or preg_match(”/^(http:\/\/info@)?([^\/]+)/i”. $$message is a variable who’s name is stored in $message. $$message is the same as $var$message is a variable $$message is a variable variable. $message is variable whereas $$message is dynamic varibale. $$holder=”bob”. $output). Use the function split split which returns an array any second element of the returned array will hold the value as abc. if $message contains "var". means $output[1] is answer. $output will give result in second index of array. if (mysql_query($sql. 8.$found).How can we create a database using PHP and mysql? $sql = ‘CREATE DATABASE my_db’.com ‘ from a string ‘http:// info@abc.com’ using regular expression of PHP? preg_match(”|[^@]*@(. eg.+)$/’. $message is variable whereas $$message is Dynamic variable. or echo $data[2].They are both variables.*)|im”. $data). } . preg_match(’/^http:\/\/. A variable variable allows us to change the name of a variable dynamically.+@(.com or echo mailto:substr(">substr). $text. 9 .How can we extract string ‘abc. $user=”bob” is equivalent to $holder=”user”. or echo $found[1]. But $message is a variable with a fixed name.com. For example.

include_once? require_once(). which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2).PHP and makeit. What are the different tables present in mysql.include_once() both the functions include and evalute the specified file only onceand if the specified file is opened previous to the present call occurrance. INNO DB 5.But require() and include() will do it as many times they are asked to do. “\n”. it will not be done again. means there should not be functions or classes or variables with the same name in abc.else { echo ‘Error creating database: ‘ .ename varchar(10)) ? Total 5 types of tables we can create 1.PHP”? Yes we can include that many times we want. Merge 4.PHP. Heap 3. The major difference between include() and require() is that in failure include produces a warning message whereas require produces a Fatal errors. 11.23. Table Types are . mysql_error() .PHP”) two times in a PHP page “makeit. but here are some things to make sure of: (including abc. with the only difference being that if the code from a file has already been included. This is a behavior similar to the include() statement. } mysql_create_db() should work 10.php 12.Can we use include (”abc. The include_once() statement includes and evaluates the specified file during the execution of the script. MyISAM 2. it will not be included again.What are the differences between require and include. the file names are case-sensitive)there shouldnt be any duplicate function names. ISAM MyISAM is the default storage engine as of MySQL 3.

Heap 3. if u not specified any table type then default will be applied and MyISAM is default Or Table Types are · ISAM(Index Sequential Access Method) · MyISAM o Static o Dynamic o Compress · Merge · Heap (Fastest tables because it stores in to the RAM) · BDB · InnoDB (Transaction safe table) When you fire the above create query MySQL will create the Dynamic table.· ISAM(Index Sequential Access Method) · MyISAM o Static o Dynamic o Compress · Merge · Heap (Fastest tables because it stores in to the RAM) · BDB · InnoDB (Transaction safe table) When you fire the above create query MySQL will create the Dynamic table. MyISAM Table Type is created. MyISAM 2. Merge . Total 5 types of tables we can create 1.

You may use –disable-cli to disable it. using the SAP Interface (SAPI) or Server Application Programming Interface named CLI which means Command Line Interface.3. imap_delete — Mark a message for deletion from current mailbox. HEAP : Fast data access. 14 How can I execute a PHP script using command line? PHP can be executed from Command Line.0. imap_mail — Send an email message.0. but was still experimental and had to be explicitly enabled with –enable-cli when running . but will loose data if there is a crash. BDB : Supports Transactions using COMMIT & ROLLBACK.23. assuming "php" is the command to invoke the CLI program. ISAM MyISAM is the default storage engine as of MySQL 3.php As of version 4. . POP3 AND LDAP? imap_body — Read the message body.3. Slower that others. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example.php". The CLI SAPI was released for the first time with PHP 4. "php myScript. By default location of php parser is so set the path of this directory and just use as following #php sample. PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. Based on Indexed Sequntial Access Method.2. Since PHP 4./configure. MyISAM: This is default. TEXT & AUTO INCRIMENT fields. Through php parse you can execute PHP script using command line. InoDB : same as BDB 13 Functions in IMAP. ISAM : same. Cannot have BLOB. The above SQL will create a MyISA table. imap_check — Check current mailbox. INNO DB 5.0 the CLI SAPI is no longer experimental and the option –enable-cli is on by default.4.

In php. it may not execute properly in command line environment. and mysql? .key_str) . 15 Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ? Its already supported. All versions before 4.ini file: set short_open_tag=on to make PHP support 16 Shopping cart online validation i. using nl2br() this will output : foo isn’t bar 18 Draw the architecture of Zend engine? CRYPT() MD5() 19 What are the current versions of apache.0.e. Example 1. etc. nl2br() is now XHTML compliant. Note: Starting with PHP 4.0.? Returns string with after inserting HTML line breaks before all newlines in a string 17 What is meant by nl2br()? AES_ENCRYPT(str. PHP. AES_DECRYPT(crypt_str.5.key_str) nl2br — Inserts HTML line breaks before all newlines in a string Description string nl2br ( string string) Returns string with ‘’ inserted before all newlines.5 will return string with ‘’ inserted before newlines instead of ‘’. how can we configure Paypal.Be aware that if your PHP script was written for the Web CGI interface.

1 20 What are the reasons for selecting lamp (linux. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. OO programming is also considered to be better at modeling the real world than is procedural programming.1. Components that manage dates. apache.1 Apache: Apache 2. Security of linux is very very more than windows. etc. Php is more faster that asp or any other scripting language. PHP) instead of combination of other software programmes. It allows for more complicated and flexible interactions.2 MySQL: MySQL 5. . mysql. an OO approach can speed development time since many objects are standard across systems and can be reused. 23 What are the features and advantages of object-oriented programming? One of the main advantages of OO programming is its ease of modification. Apache is a better server that IIS both in functionality and security. can be purchased and easily modified for a specific system. servers and operating systems? All of those are open source resource. Mysql is world most popular open source database. objects can easily be modified and added to a system there by reducing maintenance costs. We can encode data using base64_encode($string) and can decode using base64_decode($string). shopping carts. shipping. or You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password"). 21 How can we encrypt and decrypt a data present in a mysql table using mysql? AES_ENCRYPT () and AES_DECRYPT () 22 How can we encrypt the username and password using PHP? You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(”Password”).or information about latest version of Apache. Php and Mysql please visits the following sites respectively. For some systems. PHP: php5.

25 What is the use of friend function? Friend functions Sometimes a function is best shared among a number of different classes. etc). See Fig. One set of code may rely on data in multiple places. determines if it is a business day or a holiday. a change log. and "polymorphism" that increase the power and flexibility of an object. modified. order function. Y2K when the code needed to be changed to handle four numerical digits instead of two). all these pieces of code must be found. "inheritance". If a function is used multiple times in a system (i... fulfillment system. OO programming languages include features such as "class". Wednesday. Changes made to any of the code sets and data sets can cause problems through out the system..e.) An object is an abstraction of a set of real-world things (for example. February.e. a request is sent asking for specific information. Ideally. a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages. etc. If a date change is needed (i.e. It may contain functionality that manages leap years. When one object needs information from another object. order processing. Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. an object may be created around "date").. reports.e. "instance". (for example.24 What are the differences between procedure-oriented languages and objectoriented languages? Traditional programming has the following characteristics: Functions are written sequentially. . 1). it is often simply cut and pasted into each program (i. Tuesday. The information within an object is encapsulated (or hidden) from the rest of the system. date function. A system is composed of multiple objects (i. so that a change in programming can affect any code that follows it. etc. Multiple sets of code and data are required to work together. Such functions can be declared either as member functions of one class or as global functions. The object would contain all information and functionality for that thing (A dateobject it may contain labels like January. Multiple sets of code can access and modify one set of data. and tested. a piece of code that manages the date). Object-Oriented programming takes a radically different approach: Code and data are merged into one indivisible item – an object (the term "component" has also been used to describe an object. See Fig 2).. information about a particular thing should reside in only one place in a system..

by using a friend specifier in the class that is admitting them. as if they were themselves members of that class. mylinkage(). } Friends in other classes It is possible to specify a member function of another class as a friend as follows: class C { friend int B::f1(). void set_next(mylinkage* L). public: mylinkage * succ(). mylinkage * next.In either case they can be set to be friends of other classes. protected: friend void set_prev(mylinkage* L. . class mylinkage { private: mylinkage * prev. }. void mylinkage::set_next(mylinkage* L) { next = L. a global function or member function of another class provides the match. A friend declaration is essentially a prototype for a member function. mylinkage * pred(). Such functions can use all attributes of the class whichnames them as a friend. mylinkage* N). } void set_prev(mylinkage * L. mylinkage * N ) { N->prev = L. but instead of requiring an implementation with the name of that class attached by the double colon syntax.

final and volatile? element Class Interface. public yes yes yes yes yes yes yes. transient yes no no no no no no. private. final yes yes no yes yes no no. }. This is particularly powerful when using the operator overloading features of C++. class B { int f1(). . We will return to it when we look at overloading. static. It is also possible to specify all the functions in another class as friends. private yes yes yes no yes no yes. Data field Method Constructor.}. class A { friend class B. by specifying the entire class as a friend. protected. static yes yes no no yes no yes. }. modifier top level nested top level nested. transient. volatile yes no no no no no no. 26 What are the differences between public. protected yes yes yes no yes no yes. Friend functions allow binary operators to be defined which combine private data in a pair of objects. (outer) (inner) (outer) (inner).

attempting to include() a file which does not exist. Fatal errors: These are critical errors . non-critical errors that PHP encounters while executing a script . these variations are represented by twelve different error types Three are three types of errors: 1. Notices: These are trivial. such errors are not displayed to the user at all . // prints @example. Warnings: These are more serious errors . These errors cause the immediate termination of the script. and PHP's default behaviour is to display them to the user when they take place. $domain = strstr($email. 28 What is the functionality of the function strstr and stristr? string strstr ( string haystack.for example.for example. these errors are displayed to the user.com stristr() is the case insensitive version of strstr() strstr() returns part of a given string from the first occurrence of a given substring to the end of the string.although. string needle ) Returns part of haystack string from the first occurrence of needle to the end of haystack. By default.although you can change this default behaviour. 3.for example. as you will see. non-critical errors that PHP encounters while executing a script . Internally. By default. attempting to include() a file which does not exist. accessing a variable that has not yet been defined. 2. instantiating an object of a non-existent class. 3. or calling a non-existent function. echo $domain. you can change this default behaviour. such errors are not displayed to the user at all . 2. ‘@’). and PHP’s default behaviour is to display them to the user when they take place. Notices: These are trivial. . Fatal errors: These are critical errors . 1. By default. Warnings: These are more serious errors . but they do not result in script termination. or calling a non-existent function.for example.for example. instantiating an object of a non-existent class. but they do not result in script termination. For example: strstr.27 What are the different types of errors in PHP? here are three basic types of runtime errors in PHP: Three are three types of errors 1) Fatal errors 2) Parser errors 3) Startup errors. These errors cause the immediate termination of the script. By default.for example. accessing a variable that has not yet been defined. these errors are displayed to the user.

have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.00%") will return "10%2E00%25?. urldocode : Decodes URL-encoded string string urlencode(str) where str contains a string like this “hello world” and the return value will be URL encoded and can be use to append with URLs. 31 How can we get second of the current time using date function? $second = date("s"). For example: urlencode("10. This function is identical to htmlspecialchars() in all ways. URL encoded strings are safe to be used as part of URLs.stristr() is idential to strstr() except that it is case insensitive. normaly used to appned data for GET like someurl. 30 What is the functionality of the function htmlentities() and htmlsecialchars()? htmlspecialchars : Convert some special characters to HTML entities (Only the most widley used) htmlentities : Convert ALL special characters to HTML entities. urldecode() returns the URL decoded version of the given string. all characters which have HTML character entity equivalents are translated into these entities. string urldocode(str) this will simple decode the GET variable’s value Like it echo (urldecode($_GET_VARS[var])) will output “Hello world” urlencode() returns the URL encoded version of the given string. 33 What is the difference between the functions unlink and unset? . except with htmlentities(). 29 How can we convert asp pages to PHP pages? You can download asp2php front end application from the site http://asp2php.cc/.com?var=hello%world. 32 What is meant by urlencode and urldocode? urlencode : Returns a string in which all non-alphanumeric characters except -_. URL coding converts special characters into % signs followed by two hex digits.naken.cc/">http://asp2php.naken.

unset() makes a variable undefined. imagesx — Get image width. $_SESSION[’var’] = ‘value’. To destroy a session: unset($_SESSION[’name’]). We can use the session_register ($ur_session_var) function. e. To know the image height use imagesy() function.g unlink() deletes the given file from the file system. 35 How can we get the properties (size. It will simply delete the file in context unset will set UNSET the variable. height) of an image using PHP image functions? To know the Image type use exif_imagetype () function. image_type_to_extension — Get file extension for image type. .ini file: upload_max_filesize integer. or session_register($ur_session_var). width. 36 What is the maximum size of a file that can be uploaded using PHP and how can we change this? In Php. To know the Image size use getimagesize () function.unlink is a function for file system handling. unlink: is used to delete a file unset is used to destroy an eralier declared variable 34 How can we register the variables into a session? $_SESSION[’name’] = “Chinmay”. getimagesize — Get the size of an image. imagesy — Get image height. session_register(’var’). type. or Old way (deprecated): $var = ‘value’. To know the image width use imagesx () function.

and 25 seconds into script execution a call such as set_time_limit(20) is made.tbl_name…] TO ‘/path/to/backup/directory’ RESTORE TABLE tbl_name[. When an integer is used.ini file 37 How can we increase the execution time of a PHP script? Use set_time_limit(int) where int is the number of seconds forexecution of the script. 38 How can we take a backup of a mysql table and how can we restore it. . if the timeout is the default 30 seconds. The default limit is 30 seconds or. –no-data. By the use of void set_time_limit ( int seconds)Set the number of seconds a script is allowed to run. if it exists. Set max_execution_time variable in php.The maximum size of an uploaded file.tbl_name…] FROM ‘/path/to/backup/directory’ mysqldump: Dumping Table Structure andData Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). the max_execution_time value defined in the php. This is very useful if you just want to get a dump of the structure for a table. In other words. it is very commonly used in conjunction with PHP scripts to create powerful and dynamic server-side applications. You can change maximum size of a file set upload_max_filesize variable in php. no time limit is imposed.ini file to your desired time in second. –no-create-info. -t. the value is measured in bytes. Don’t write table creation information (the CREATE TABLE statement). If seconds is set to zero. The dump will contain SQL statements to create the table and/or populate the table. On top of that. the script returns a fatal error. Default valueis 30. If it’s set to 0 it’s unlimited. When called. ? To backup: BACKUP TABLE tbl_name[. Don’t write any row information for the table. the script will run for a total of 45 seconds before timing out. PHP / MySQL Tutorial MySQL is currently the most popular open source database server in existence. set_time_limit() restarts the timeout counter from zero. If this is reached.ini. -d.

Age. It is aimed at teaching those who have web hosts with PHP and MySQL already installed. If you already have that base covered feel free to skip on to the next lesson. Height). If you are unsure. Each row will have 1 value for each and every column. However. An individual column must be created for each type of data you wish to store (i. MySQL continues to improve with each release (currently version 5). and Customers. Each table would then contain columns specific to these three areas. Age. A relational database is much more oriented to the human mind and is often preferred over the gabble-de-gook flat database that are just stored on hard drives like a text file. The columns define which kinds of information will be stored in the table. Date. With a database you can group different parts of your business into separate tables to help store your information logically. For example a table with columns (Name. the Employees table might have the following columns: Hire. We will talk about and show a few examples in the coming lessons. 65. If all this relational database talk is too confusing. don't despair. MySQL is a relational database. Weight-lbs) could have a row with the values (Bob. This tutorial focuses heavily on using MySQL in a PHP environment. To help store information related to each employee. For example. Supervisors. Why Use a Database? Databases are most useful when it comes to storing information that fits into logical categories. please contact your web host. and it has become widely popular with individuals and businesses of many different sizes. a row contains the actual values for these specified columns.MySQL has been criticized in the past for not supporting all the features of other popular and more expensive DataBase Management Systems. Learn MySQL Before you begin this tutorial you should have a basic knowledge of the information covered in our PHP and HTML tutorials. Position. MySQL Admin This lesson covers the different options you have available to you for administering your MySQL service after it is successfully installed. 165). On the other hand. Weight.e. say that you wanted to store information of all the employees in a company. What is a Database? A database is a structure that comes in two flavors: a flat database and a relational database. In a relational structured database there are tables that store data. Example tables might be: Employees. MySQL Command Line . Age. and Salary.

Mac and Linux. most of the examples are ready for you to copy. so the best way to learn is with direct examples. Type the keyword "cmd" into the text field and press Enter to launch Window's command line interface.com Navicat . the very popular phpMyAdmin tool should come with your web hosting plan. $result = mysql_query("SELECT * FROM example") . Because this tutorial focuses on the combination of MySQL and PHP. then you can simply use any command line interface to execute MySQL queries. Those of you with MySQL installed on your Microsoft Windows operating system can reach the command line by going to the Start Menu and choosing "Run. MySQL GUI With so many free MySQL administration tools available. many developers favor these free Graphical User Interfaces over the command line. and most queries consist entirely of English words! Strategies to Learn MySQL The MySQL language is not as complicated as most programming languages. Virtual or Dedicated hosting solution. Very few special characters and symbols are required to create a MySQL query.A popular web interface that is included with almost every type of Shared. and run on your web server.If you are an old-school programmer that has no need for a graphical user interface. paste. CAPITALIZATION in MySQL Queries There are many keywords in MySQL.". as opposed to harder programming languages like C or C++. The most popular options include: phpMyAdmin . MySQL Administrator ..A powerful tool developed by the folks at MySQL. MySQL Syntax The great thing about everything you do in MySQL is that the "code" is very easy for humans to read.. MySQL phpMyAdmin As previously mentioned. This helps draw them out from the rest of the code and makes them much easier to read. Below is an example of a MySQL query written in PHP that retrieves all the data from a MySQL table named "example". and a good programming habit when using ANY of these words is to capitalize them.A purchasable MySQL admin tool for Windows.

Instead they require that you use the PHP/MySQL administration tools on the web host control panel to create these databases. you would group them into one database to make the management process easier. it is best to take it one lesson at a time and stop when you feel frustrated. Do not worry if it takes you more than a week to finish this tutorial. .That line of code is valid PHP. Creating Your First Database Most web hosts do not allow you to create a database directly through a PHP script. you will be much more well-informed about the MySQL database system than if you rushed through it in one sitting. As you probably can tell "SELECT" and "FROM" are the MySQL keywords used in this query. Because all of our scripts are going to be placed on the server where MySQL is located the correct address is localhost. but it also contains valid MySQL. Capitalizing them allows you to tell from a quick glance that this query selects data from a table. If you take the time to progress slowly. Create a database and assign a new user to this database. then you would need to enter the correct url (ask your web host for specifics on this). For all of our beginning examples we will be using the following information: Server – localhost Database – test Table – example Username – admin Password . You can view a complete list of MySQL keywords at List of Reserved MySQL Words. If the MySQL server was on a different machine from where the script was running. Learn at Your Own Pace When learning MySQL.1admin Note: The table may change in the advanced lessons. The text that appears between the quotations "SELECT * FROM example". Rather a MySQL database is a way of organizing a group of tables. but everything else will remain the same! The server is the name of the server we want to connect to. is the MySQL code. If you were going to create a bunch of different tables that shared a common theme. MySQL Database A MySQL database is nothing in itself. but don't worry about memorizing them. You could program relentlessly in MySQL for years without ever using all of the MySQL keywords.

usernam ame. ?> Display: Connected to MySQL If you load the above PHP script to your webserver and everything works properly. If you choose a different set of login information.admin . username. MySQL localhost If you've been around the internet a while.localhost Username . In our example above these arguments were: Server . "admin". This is done with the MySQL connect function. we assume that the MySQL service is running on the same machine as the script. you should have created a new database and assigned a user to it. Status Check So far. If you are up-to-date. MySQL Connect Before you can do anything with MySQL in PHP you must first establish a connection to your web host's MySQL database.php page. and password do not have to match ours. We will be making our first table in an upcoming lesson. "1admin") or die(mysql_error()). and password. You should not have created a table yet. In this example of a connection script. you can use localhost as the address you wish to connect to. you'll know that IP addresses are used as identifiers for computers and web servers. table. When the PHP script and MySQL are on the same machine.Your database. remember to insert your own information when copying the scripts in this tutorial. then you should see "Connected to MySQL" displayed when you view the . then continue the tutorial. Server. PHP & MySQL Code: <?php mysql_connect("localhost". localhost is a shortcut to just have the machine connect to itself. The mysql_connect function takes three arguments. If your MySQL service is running at a separate location you will need to insert the IP address or URL in place of localhost. Please contact your web host for more details if localhost does not work. echo "Connected to MySQL<br />".

PHP & MySQL Code: <?php mysql_connect("localhost". "admin".there is an error in processing the connection! Double-check your username. Choosing the Working Database After establishing a MySQL connection with the code above. Below is how you could imagine a MySQL table.. you then need to choose which database you will be using with this connection. password. R = Row) C1 (Name) R1 R1 C1 (John) R2 R2 C1 (Big Sally) R3 R3 C1 (Tiny Tim) R4 R4 C1 (Normal Ned) C2 (Age) R1 C2 (21) R2 C2 (27) R3 C2 (6) R4 C2 (35) C3 (Weight) R1 C3 (120) R2 C3 (400) R3 C3 (35) R4 C3 (160) . echo "Connected to MySQL<br />". mysql_select_db("test") or die(mysql_error())." code displays an error message in your browser if --you've probably guessed it -. while the rows contain the actual data. The columns specify what the data is going to be. "1admin") or die(mysql_error()). or server if you receive this error. The table gets this done by making the table up of columns and rows. ?> Display: Connected to MySQL Connected to Database MySQL Tables A MySQL table is completely different than the normal table that you eat dinner on.. echo "Connected to Database". (C = Column.Password . the goal is to store information in an orderly fashion.1admin The "or die(mysql. This is done with the mysql_select_db function. In MySQL and other database systems.

// Create a MySQL table in the selected database mysql_query("CREATE TABLE example( id INT NOT NULL AUTO_INCREMENT. mysql_select_db("test") or die(mysql_error()). In future lessons we will be using this table. We are now going to design a MySQL query to summon our table from database land. PRIMARY KEY(id). Create Table MySQL Before you can enter data (rows) into a table. not the R# and C#! This table has three categories. Age. echo "Table Created!". "1admin") or die(mysql_error()). 'mysql_query ("CREATE TABLE example' .We added the row and column number (R# C#) so that you can see that a row is side-to-side. you must first define what kinds of data will be stored (columns). name VARCHAR(30). Display: Wow! That's a lot of code all at once! Let's get down in the dirt and figure this stuff out. and Weight. so be sure to enter this query correctly! PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost". We will be going through the code line by line. "admin". This table has four entries. or "columns". of data: Name. while a column is up-to-down. or in other words. four rows. In a real MySQL table only the value would be stored. age INT)") or die(mysql_error()).

a-z). numbers.This stands for integer or whole number. 'id' has been defined to be an integer. AUTO_INCREMENT . "Character" means that you can put in any kind of typed information in this column (letters. contacts. An entry is NOT NULL only if it has some value. 'id INT NOT NULL AUTO_INCREMENT' Here we create a column "id" that will automatically increment each time a new entry is added to the table. The two capitalized words are reserved MySQL keywords. The number inside the parentheses sets the maximum number of characters.' Our third and final column is age. which stores an integer. while something with no value is NULL. and so on. such as: employee_information. In this case. NOT NULL . The . This means that no two ids can be the same. etc). as it is all automatically calculated within MySQL. or customer_orders. MySQL already knows what to do with an integer. 'name VARCHAR(30). symbols. Notice that there are no parentheses following "INT". the max is 30. the second row id = 2. or else we will run into trouble. Here we have made "id" the PRIMARY KEY for this table.These are actually two keywords. The column "id" is not something that we need to worry about after we create this table.' Here we make a new column with the name "name"! VARCHAR stands for "variable character". Reserved MySQL Keywords: Here are a few quick definitions of the reserved words used in this line of code: INT . We will most likely only be using this name column to store characters (A-Z. 'PRIMARY KEY (id)' PRIMARY KEY is used as a unique identifier for the rows. This is why we made "id" an auto-incrementing counter in the previous line of code. 'age INT.Each time a new entry is added the value will be incremented by 1. It's "variable" because it can adjust its size to store as little as 0 characters and up to a specified maximum number of characters. The word "example" is the name of our table. It is a good idea to use descriptive names when creating a table. This will result in the first row in the table having an id = 1. as it came directly after "CREATE TABLE". the third row id = 3. Clear names will ensure that you will know what the table is about when revisiting it a year after you make it.The first part of the mysql_query told MySQL that we wanted to create a new table. but they combine together to say that this column cannot be null.

mysql_query("INSERT INTO example (name. age) VALUES('Timmy Mellow man'. "admin".' This will print out an error if there is a problem in the table creation process. '23' ) ") or die(mysql_error()). If you try to place a 500 word essay into a column that only accepts integers of size three. age) VALUES('Sandy Smith'.648 to 2. mysql_select_db("test") or die(mysql_error()). '21' ) ") or die(mysql_error()).147. you will end up with a nasty error! Inserting Data Into Your Table Now that you have created your table. When inserting data it is important to remember the exact names and types of the table's columns. '15' ) ") or die(mysql_error()). let's put some data into that puppy! Here is the PHP/MySQL code for inserting data into the "example" table we created in the previous lesson. .147.possible integer values that can be stored in an "INT" are -2.483.483.647. MySQL Insert When data is put into a MySQL table it is referred to as inserting data. mysql_query("INSERT INTO example (name. "1admin") or die(mysql_error()). PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost". // Insert a row of information into the table "example" mysql_query("INSERT INTO example (name. which is more than enough to store someone's age! 'or die(mysql_error()). age) VALUES('Bobby Wallace'.

data is retrieved with the "SELECT" keyword. In MySQL. then copy and paste. Here we enter the name Timmy Mellow man for "name". we will output the first entry of our MySQL "examples" table to the web browser. Using MySQL SELECT & FROM Before attempting this lesson. we will cover the code line by line. Once again. you would first select the desired information.echo "Data Inserted!". ?> Display: This code is much simpler to understand than the create table code. and 23 for "age". 'mysql_query("INSERT INTO example' Again we are using the mysql_query function. '23' ) ")' "(name. Be sure to note the location and number of apostrophes and parentheses in the PHP code. as this is where a lot of beginner PHP/MySQL programmers run into problems. Think of SELECT as working the same way as it does on your computer. age)" are the two columns we want to add data into. "INSERT INTO" means that data is going to be put into a table. The name of the table we specified to insert data into was "example". as will be most of the MySQL queries you will learn in the rest of this tutorial. Retrieving Data With PHP & MySQL Usually most of the work done with MySQL involves pulling down data from a MySQL database. In this lesson we will cover the most common MySQL Query that is used to retrieve information from a database. preferably the same data that we had in the MySQL Insert lesson. In this example. '(name. MySQL Query So far we have seen a couple different uses of PHP's mysql_query function and we'll be seeing more of it as nearly all MySQL in PHP is done through the MySQL Query function. age) VALUES('Timmy Mellow man'. If you wanted to copy some information in a document. . be sure that you have created a table that contains some data. We have already created a new table and inserted data into that table. "VALUES" means that what follows is the data to be put into the columns that we just specified.

"1admin") or die(mysql_error()). // Print out the contents of the entry echo "Name: ". but we wanted to explain this MySQL statement in greater detail again! . 'SELECT * FROM example' Yes. $result. so we need to store it in a variable. Although the MySQL code is simple. // Retrieve all the data from the "example" table $result = mysql_query("SELECT * FROM example") or die(mysql_error()). "admin". mysql_select_db("test") or die(mysql_error()).$row['age']. printing out the information with PHP is somewhat more involved.PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost". // store the record of the "example" table into $row $row = mysql_fetch_array( $result ). Below is a step-by-step walkthrough of the code.$row['name']. this is a partial repeat of the same line of code. ?> Display: Name: Tim Mellowman Age: 23 This is an example of how to use MySQL's SELECT statement in PHP. We want to use this Resource in our PHP code. '$result = mysql_query("SELECT * FROM example")' When you perform a SELECT query on the database it will return a MySQL Resource that holds everything from your MySQL table. echo " Age: ". "example".

When we pass $result into the mysql_fetch_array function -mysql_fetch_array($result) -.' $result is now a MySQL Resource containing data from your MySQL table. '$row = mysql_fetch_array( $result ). Additional PHP functions are required to extract the data from this Resource.an associative array (name. This lesson will teach you how and why to use mysql_fetch_array in your PHP Scripts. "example". age) is returned. The asterisk is the wild card in MySQL which just tells MySQL to include every single column for that table. that is for sure. so be sure to use capitalization in your PHP code that matches the MySQL column names! MySQL Fetch Array MySQL doesn't have a Fetch Array function. mysql_fetch_array: Why Use It? Do you know what is returned when you used the mysql_query function to query a MySQL database? It isn't something you can directly manipulate.In English. it is a MySQL Resource. A Row of Data The mysql_fetch_array function takes a MySQL query resource as an argument ($result) and returns the first row of data returned by the mysql_query. PHP and MySQL Code: <?php $result = mysql_query("SELECT * FROM example"). . These names are the keys to extracting the data from our associative array. mysql_fetch_array is actually a PHP function that allows you to access data stored in the result returned from a successful mysql_query. PHP is case sensitive when you reference MySQL column names. ?> The value that mysql_query returns and stores into $result is a special type of data. but it is not yet visible to visitors of your website. In our MySQL table "example. Our table example basically looks like the table below. Here is a sample SELECT query of a table we created in the MySQL Create Table lesson. Data is being stored in $result. To get the name we use $row['name'] and to get the age we use $row['age']." there are only two fields that we care about: name and age. If you have been jumping around our MySQL Tutorial then you would have already seen this function popping up all over the place. this line of code reads "Select every entry from the table example".

23 This is just what we expected would happen! Now. Fetch Array While Loop As we have said. $row = mysql_fetch_array($result) or die(mysql_error()). When we fetch an array from our MySQL Resource $result it should have Timmy's name and age in it. third. Here is the code to print out the first MySQL Result row. but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage. the cool thing about mysql_fetch_array is that you can use it again on the same MySQL Resource to return the second. PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT * FROM example". echo $row['name']. It would be nice if we could get all our results from a MySQL Resource in an easy to do script. $row['age']. Getting a Row of Data using mysql_fetch_array mysql_fetch_array returns the first row in a MySQL Resource in the form of an associative array. Sounds like an awfully repetitive task. In our table example these are: name and age. . You can keep doing this until the MySQL Resource has reached the end (which would be three times in our example). " . fourth and so on rows. $result = mysql_query($query) or die(mysql_error()).example MySQL Table: name Timmy Mellowman Sandy Smith Bobby Wallace age 23 21 15 The first row of data in this table is "Timmy Mellowman" and "23". ?> Display: Timmy Mellowman . the mysql_fetch_array function returns an associative array.". The columns of the MySQL Result can be accessed by using the column names of the table.

When there are no more rows the function will return FALSE causing the while loop to stop! Now that we know what we need to do and how to go about doing it. $result = mysql_query($query) or die(mysql_error()). $row['age']. PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT * FROM example". " . } ?> Display: Timmy Mellowman .21 Bobby Wallace . the code pretty much writes itself. while($row = mysql_fetch_array($result)){ echo $row['name'].23 Sandy Smith .". The . echo "<br />".15 And there we have all the rows from our example table! You could apply this script to any MySQL table as long as you change both the table name in the query and the column names that we have in the associative array.If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things: We will get a new row of MySQL information that we can print out each time the while loop checks its conditional statement. MySQL Select You have seen two types of MySQL queries thus far: the query which we used to create a table and the query we used to insert data into our newly created table. Just kidding! Here is the code that will print out all the rows of our MySQL Resource. so let's move on to the next lesson.

"admin". echo "</td><td>". "1admin") or die(mysql_error()). we get to use the data in our MySQL database to create a dynamic PHP page. mysql_select_db("test") or die(mysql_error()). Retrieving Information from MySQL Finally. PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost". which is used to get information from the database. if you don't understand the HTML or PHP code. echo "<tr> <th>Name</th> <th>Age</th> </tr>". // Get all the data from the "example" table $result = mysql_query("SELECT * FROM example") or die(mysql_error()). . // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>". be sure to check out the HTML and/or PHP Tutorial(s). Remember. } echo "</table>". echo "<table border='1'>". echo "</td></tr>". echo $row['age']. In this example we will select everything in our table "example" and put it into a nicely formatted HTML table.query in this lesson is SELECT. so that its data can be used in our PHP script. echo $row['name'].

We can retrieve the next associative array from our MySQL Resource. then you would see each additional row appear in the above table. 'while($row = mysql_fetch_array( $result )' The mysql_fetch_array function gets the next-in-line associative array from a MySQL result. $result now holds the result from our mysql_query.. This function can be called as many times as you want. Since we want to use this data in our table we need to store it in a variable.?> Display: Name Timmy Mellowman Sandy Smith Bobby Wallace Age 23 21 15 Because we only had three entries in our table. If you do not understand the above PHP. In our MySQL table "example" there are only two fields that we care about: name and age. The asterisk is the wild card in MySQL which just tells MySQL to retrieve every single field from the table. this line of code reads "Select everything from the table example". $result. as False is returned when it reaches the end and this will cause the while loop to halt. so that we can print out the name and age of that person. the data is returned as a MySQL result. three rows appeared above. but it will return FALSE when the last associative array has already been returned. By putting it in a while loop it will continue to fetch the next array until there is no next array to fetch. you can view our PHP Array Tutorial & PHP Loop Tutorial. we can kill two birds with one stones. 'SELECT * FROM example' In English..' When you select items from a database using mysql_query. These fields are the keys to extracting the data from our associative array. We can tell the while loop to stop printingn out information when the MySQL Resource has returned the last array. To get the name we use $row['name'] and to get the age we use $row['age']. '$result = mysql_query. By placing this function within the conditional statement of the while loop. If you added more entries to your database's table. Practice What You Have Learned .

We will be assuming the data from a previous lesson for the following examples. mysql_select_db("test") or die(mysql_error()). See which one you like best! By now you should be starting to understand how powerful PHP and MySQL are when used together. "admin". Here's how to do it. Sandy. In our example we will want to select all rows that have the string "Sandy Smith" in the "names" column (mathematically: {name column} = "Sandy Smith"). To select Sandy only we could either specify Sandy's age (21) or we could use her name (Sandy Smith).Use the query that we have provided or make a new one and try putting it into a formatted HTML table. Imagine trying to create an HTML table of 6000 entries without using a MySQL database and a PHP while loop! MySQL Where In a previous lesson we did a SELECT query to get all the data from our "example" table. WHERE is used in conjuction with a mathematical statement. and Bobby. It might be useful to try out other methods of HTML formatting as well. Those entries that do not pass the test will be left out. "1admin") or die(mysql_error()). PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost". The tasks that you can complete with MySQL and PHP would be nearly impossible to do by hand in HTML. so we will use her name as our requirement. // get the first (and hopefully only) entry from the result $row = mysql_fetch_array( $result ). Being Selective With Your MySQL Selection There are three entries in our "example" table: Tim. If we wanted to select only certain entries of our table. . // Get a specific result from the "example" table $result = mysql_query("SELECT * FROM example WHERE name='Sandy Smith'") or die(mysql_error()). then we would use the keyword WHERE. In the future there may be other people who are 21. WHERE lets you specify requirements that entries must meet in order to be returned in the MySQL result.

. you could make 10 different queries. one for each age 20. selecting everyone who is their 20's from or MySQL table. how could you go about doing it? With the tools you have now. The '%' tells MySQL to ignore the text that would normally appear in place of the wildcard.$row['age']. we can utilize wildcards to pick out all strings starting with a 2. "<br />"." . 22. MySQL Query WHERE With Wildcard To solve our problem from before.. 25.but that seems like more work than we need to do." . For example '2%' would match the following: 20. In MySQL there is a "wildcard" character '%' that can be used to search for partial matches in your database. a20.". // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row echo $row['name']. PHP & MySQL Code: <?php // Connect to MySQL // Insert a row of information into the table "example" $result = mysql_query("SELECT * FROM example WHERE age LIKE '2%' ") or die(mysql_error()).// Print out the contents of each row into a table echo $row['name']. ?> Display: Sandy Smith – 21 MySQL Wildcard Usage '%' If you wanted to select every person in the table who was in the ir 20's. '2%' would not match the following: 122.". and 2! On the other hand. 2avkldj3jklsaf. 21. 2000000. } ?> .$row['age']. and 32.

the values are already sorted and easy to read. "admin". Then when you use mysql_fetch_array to print out the result. The code from MySQL Select looked like. Note: The wildcard was used for example purposes only. and end of the string. and more. mysql_select_db("test") or die(mysql_error()). post count. MySQL Order By It would be nice to be able to make MySQL results easier to read and understand.. Using a wildcard in this example would select unwanted cases.. // Get all the data from the "example" table $result = mysql_query("SELECT * FROM example") . view count. The way to order your result in MySQL is to use the ORDER BY statement.ORDER BY Let's use the same query we had in MySQL Select and modify it to ORDER BY the person's age. Experiment with it so you can see for yourself how powerful this little trick can be. What ORDER BY does is take the a column name that you specify and sort it in alphabetical order (or numeric order if you are using numbers). For example. thread title. like a 2 year old and your 200 year old great-great-greatgrandparents. If you really wanted to explicilty select people who are in their 20's you would use greater than 19 and less than 30 to define the 20's range. some forums let you sort by date. Ordering is also used quite frequently to add additional functionality to webpages that use any type of column layout. A common way to do this in the real world is to order a big list of items by name or amount. PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost".Display: Timmy Mellowman – 23 Sandy Smith . middle. Sorting a MySQL Query . "1admin") or die(mysql_error()).21 You can use this wildcard at the beginning.

be sure that your ORDER BY appears after the SELECT . PHP & MySQL Code: <?php // Make a MySQL Connection mysql_connect("localhost".. echo "<table border='1'>". } echo "</table>". "admin".. . echo $row['name']. echo "</td></tr>". echo "</td><td>". mysql_select_db("test") or die(mysql_error()).or die(mysql_error()). // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>". ?> Display: Name Timmy Mellowman Sandy Smith Bobby Wallace Age 23 21 15 What we need to do is add on to the existing MySQL statement "SELECT * FROM example" to include our new ordering requirement. FROM part of the MySQL statement. echo "<tr> <th>Name</th> <th>Age</th> </tr>". echo $row['age']. "1admin") or die(mysql_error()). When you choose to order a column.

Sometimes it may be easier to just tweak your MySQL query instead of trying to mess around in PHP. . but in most real world MySQL usage you will often need to get data from multiple tables in a single query. echo "<table border='1'>". echo $row['age']. This is fine for simple tasks. // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>". MySQL Joins Thus far we have only been getting data from one table at a time. echo "</td><td>".// Get all the data from the "example" table $result = mysql_query("SELECT * FROM example ORDER BY age") or die(mysql_error()). ?> Display: Name Bobby Wallace Sandy Smith Timmy Mellowman Age 15 21 23 Presto! We have an ordered MySQL result! Notice that we didn't have to change any of our PHP code. echo $row['name']. echo "<tr> <th>Name</th> <th>Age</th> </tr>". } echo "</table>". echo "</td></tr>". Remember this whenever you're editing a PHP script that uses MySQL.

MySQL Join Simple Example Let's imagine that we wanted to SELECT all the dishes that were liked by a family member. If you remember from the previous lesson. this is a situation when we need to use the WHERE clause. In th e "family" table. the Position column contains all the members of the family and their respective ages. In the "food" table the Position column contains the family member who enjoys that dish. We want to SELECT all the dishes WHERE a family member likes it. MySQL Join Table Setup We like to show examples and code before we explain anything in detail. family Table: Position Dad Mom Daughter Dog food Table: Meal Steak Salad Spinach Soup Tacos Dad Position Dad Mom Age 41 45 17 The important thing to note here is that the column Position contains information that can tie these two tables together. The two tables we will be using relate to a families eating habits. so here is how you would combine two tables into one using MySQL. joined table. It's only through a shared column relationship such as this that tables can be joined together. so remember this when creating tables you wish to have interact with each other. .The act of joining in MySQL refers to smashing two or more tables into a single table. We will be performing a generic join of these two tables using the Position column from each table as the connector. This means everything you have learned so far can be applied after you've created this new.

Meal ". "WHERE family.Position = food. food ". // Print out the contents of each row into a table while($row = mysql_fetch_array($result)){ echo $row['Position']. you can either create them using our MySQL Create Table lesson or do it manually yourself. " . echo "<br />".Position.". food.Position" will restrict the results to the rows where the Position exists in both the "family" and "food" tables. "FROM family. } ?> The statement "WHERE family. $row['Meal']. Compare the Tables: Position Dad Mom Daughter Dog Age 41 45 17 .Position". Let's analyze the tables to make sure we agree with these results.Note: This example assumes you have created the MySQL tables "food" and "family". Display: Dad – Steak Mom – Salad Dad – Tacos Those are the results of our PHP script.Position = food. PHP and MySQL Code: <?php // Make a MySQL Connection // Construct our join query $query = "SELECT family. If you do not have either of them created. $result = mysql_query($query) or die(mysql_error()).

Meal Steak Salad Spinach Soup Tacos Position Dad Mom Dad Our results show that there were three meals that were liked by family members. This extra consideration to the left table can be thought of as special kind of preservation. MySQL LEFT JOIN In the previous lesson. the syntax is quite different and somewhat more complex. Being "on the left" simply refers to the table that appears before the LEFT JOIN in our SQL statement. the LEFT JOIN gives extra consideration to the table that is on the left. Each item in the left table will show up in a MySQL result. Joins are a very hard concept to grasp for beginning MySQL developers. MySQL LEFT JOIN Explanation How is a LEFT JOIN different from a normal join? First of all. This lesson will teach you how to do a specialized join: left join. MySQL family and food Tables: Position Dad Mom Daughter Dog Age 41 45 17 Meal Position . MySQL Join and LEFT JOIN Differences Here are the tables we used in the previous Mysql Joins lesson. even if there isn't a match with the other table that it is being joined to. Note: This is a very simple example of a join. Nothing tricky about that. And by manually perusing the tables it looks like there were indeed three meals liked by family members. Mysql Joins we learned how to do a basic join of two tables. If you do not understand it yet do not despair. Besides looking different.

$result = mysql_query($query) or die(mysql_error()). Let's see if the results are what we expected. This is because a left join will preserve the records of the "left" table. even if they do not have a favorite dish in our food table.Position". "ON family. MySQL LEFT JOIN Example The code below is the exact same as the code in the previous lesson. food.Position Result: Dad – Steak Mom – Salad Dad . food WHERE food.Position = family.Position.Meal ".Meal. except the LEFT JOIN has now been added to the query.Steak Salad Spinach Soup Tacos Dad Mom Dad We executed a simple query that selected all meals that were liked by a family member with this simple join query: Simplified MySQL Query: SELECT food. PHP and MySQL Code: <?php // Make a MySQL Connection // Construct our join query $query = "SELECT family.Position = food.Position FROM family. all the family members be listed. . family. "FROM family LEFT JOIN food ".Tacos When we decide to use a LEFT JOIN in the query instead.

and WHERE. On the other hand. Unfortunately for you.// Print out the contents of each row into a table while($row = mysql_fetch_array($result)){ echo $row['Position']. " . MySQL Update Example Once again we will be working with the data from a previous example. SET. including those who don't yet have a favorite meal in the food table! Please feel free to play around with LEFT JOIN until you feel like you have a solid grasp of it. echo "<br />". This stuff isn't easy! MySQL Update Imagine that you have a MySQL table that holds the information of all the employees in your company. One of the columns in this table is called "Seniority" and it holds an integer value of how many months an employee has worked at your company. you could master MySQL and have an automated script that you run each month to get the job done for you. In this lesson you will learn how to replace the existing data of a MySQL table with freshly supplied up-to-date data using the UPDATE MySQL query. } ?> Display: Dad – Steak Dad – Tacos Mom – Salad Daughter – Dog – Success! The LEFT JOIN preserved every family member. UPDATE . You may be thinking that you'll have to open up your MySQL administration tool and edit each entry by hand.The new values to be placed into the table follow SET . That would take hours. Our job now is to update her age using MySQL commands like UPDATE.Performs an update MySQL query SET . your job is to update these numbers every month. $row['Meal']. Sandy has just had a birthday and she now 22 years old.".

MySQL Delete Maintenance is a very common task that is necessary for keeping MySQL tables current. echo $row['name']. tell MySQL to perform the deletion. We need to choose a table. you may even need to delete items from your database. In a table where Sandy is not the only entry." . "<br />". Some potential reasons for deleting a record from MySQL include when: someone deletes a post from a forum. an employee leaves a company.". This is how we do it. and provide the requirements that a record must have for it to be deleted. and a more sophisticated solution would be necessary.22 Now it is important to note that this query would have updated ALL records that had an age of 21 to the new age of 22. // get the first (and hopefully only) entry from the result $row = mysql_fetch_array( $result ).Limits which rows are affected PHP & MySQL Code: <?php // Connect to MySQL // Get Sandy's record from the "example" table $result = mysql_query("UPDATE example SET age='22' WHERE age='21'") or die(mysql_error()).WHERE . From time to time. this may become a problem. .$row['age']. ?> Display: Sandy Smith . Say we want to delete the youngest employee from our previously created table because he has to go back to school. $result = mysql_query("SELECT * FROM example WHERE age='22'") or die(mysql_error()). or you're trying to destroy your records before the federalies come! MySQL DELETE Example The DELETE query is very similar to the UPDATE Query in the previous lesson.

be sure to back up the table/database in case your script takes off a little more than desired. As long as you take caution when using this powerful query you should not run into any problems. This fact makes the whole backup and restore process extremely simple and painless once you have figured out how to do it. or your spending information -. MySQL DELETE Tips Before performing a large delete on a database. or SSH script you use. all of the backups will fit into two types of backups: a dump or raw backup. no matter which application. Test your delete queries before even thinking about using them on your table. employee information.you are going to need to choose a backup schedule that meets your needs. MySQL Dump A MySQL dump is a bit slower than a raw backup because it creates all the SQL queries required to create the tables of that database. Depending on what you're using your databases for -.PHP & MySQL Code: <?php // Connect to MySQL // Delete Bobby from the "example" MySQL table mysql_query("DELETE FROM example WHERE age='15'") or die(mysql_error()). as well as all the insert queries required to place the information back into the database's tables. chances are you should be doing weekly or even daily backups.be it to store forum messages. MySQL Database Backups If you're storing anything in MySQL databases that you do not want to lose. control panel tool. Different Ways to Get That Backup Done There are many paths you can take to create a MySQL backup. . However. You may or may not know that MySQL databases are just files that are stored on your web server. Since Bobby was the only 15 year old this was not a problem. ?> It is important to note that this query would have deleted ALL records that had an age of 15.

Aggregate Functions After you have mastered the basics of MySQL.Constituting or amounting to a whole. Below that title should be a listing of every database that you have created. total. it's time to take the next step and take on Aggregate Functions. The most common types of aggregate functions let you find out things like the minimum. The trick to understanding aggregate functions is often understanding what kind of data is being grouped and analyzed. MySQL Backup in Control Panel cPanel cPanel is the most widely used web host control panel at this time. without the assistance of your hosts control panel. However. we can assume that MySQL's aggregate functions are something that will be very top-level. ~American Heritage Dictionary With this type of wording. or in other words. so we thought it would make sense to provide a walkthrough specifically for cPanel. let's review the definition of aggregate. MySQL Raw Backup A MySQL Raw Backup is quicker because it does not translate the contents of the database into human readable SQL queries. not many control panels support this type of backup. . This will bring you to the backup application that allows you to generate and download complete backups for your site. then run SSH to your web server and do the following (taken from MySql. Before we talk about what they are. From the application selection screen click "Backup".com): mysqldump --tab=/path/to/some/dir --opt db_name If you were to open up a MySQL dump file you would see a slew of SQL queries that you would probably be able to understand (if you've already read through this whole tutorial!). That's it! Now just be sure that you have a regular backup schedule. maximum and even the average of a "grouped" set of data. look for the title "Download a SQL Database Backup" or something similar. Simply click on the name of the database you want to backup and save it to your computer. so do not worry if your hosting provider doesn't have this option set up for you. the opposite of detailed. To back up a database individually. just in case the unthinkable happens and your web host loses all your database information! MySQL GROUP BY .If you want to perform the mysql dump manually. as it relates to MySQL: Aggregate .

MySQL GROUP BY . Below is the MySQL table products. then each of the records). and the GROUP BY PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT type. In this case we would be "grouping" by the product type and finding the minimum price of each group. Our query needs to return two columns: product type and minimum price.99 3.The Data Before we can start throwing around these fancy functions. MIN. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row. we want to use the type column as our group. Additionally. create table.99 89.e.50 34. MIN(price) FROM products GROUP BY type".95 32. The SELECT statement we are about to use will look different because it includes an aggregate function.99 21.73 GROUP BY . You can either run this SQL statement in your MySQL administrator software or use MySQL to execute the queries (i. let's build an appropriate table that has enough data in it to be meaningful to us. $result = mysql_query($query) or die(mysql_error()).97 3. Below is the SQL for our "products" table. You can download the products.Creating Your First "Group" Imagine that our store was running an advertisement in the newspaper and we wanted to have a "bargain basement" section that listed the lowest price of each product type.sql file from our website.55 8. Products Table: id 123451 123452 123453 123454 123455 123456 123457 123458 name Park's Great Hits Silly Puddy Playstation Men's T-Shirt Blouse Electronica 2002 Country Tunes Watermelon type Music Toy Toy Clothing Clothing Music Music Food price 19. // Print out result while($row = mysql_fetch_array($result)){ .

echo $row['type']. If you missed the Aggregate Introduction Lesson.$". then GROUP BY would not be all that useful.COUNT() This lesson will teach you how to use the aggregate function COUNT(). and you want to find out some statistical information like the minimum. " . please check it out now. The next few lessons will provide a walkthrou gh for using other popular MySQL aggregate functions in conjunction with the GROUP BY statement. Toy. For example. If you only had one product of each type. When we GROUP BY type then we get one result for each of these types.99 Toy .$3. but otherwise it isn't any different than a normal SELECT statement. Clothing and Food. or other top-level info.$32. GROUP BY only shines when you have many similar things. as it explains many concepts used in this lesson! .$3. } ?> Our "products" table has four types of products: Music. you would use GROUP BY. if you have a number of products of the same type.73 Music .$8. $row['MIN(price)'].50 Food . MySQL Aggregate Functions . Some technical rules of GROUP BY: The column that you GROUP BY must also be in your SELECT statement. Display: Clothing . Remember to group by the column you want information about and not the one you are applying the aggregate function on.99 MySQL GROUP BY – Review Group BY is good for retrieving information about a group of data. statement. echo "<br />". maximum. In our above example we wanted information on the type column and the aggregate function was applied to the price column.

99 89. Clothing and Food.50 34. PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT type.Counting Records The COUNT function is an aggregate function that simply counts all the items that are in a group.99 21.". Just as we did in the aggregate introduction lesson. $row['COUNT(name)'] .95 32. For a slight change of pace." ". Products Table: id 123451 123452 123453 123454 123455 123456 123457 123458 name Park's Great Hits Silly Puddy Playstation Men's T-Shirt Blouse Electronica 2002 Country Tunes Watermelon type Music Toy Toy Clothing Clothing Music Music Food price 19. } . Below is the MySQL table "products". echo "<br />".97 3.We will be using the "products" table that we constructed to display the use of MySQL's COUNT function.55 8. You can download the products.99 3. One use of COUNT might be to find out how many items of each type there are in the table. we are going to GROUP BY type to create four groups: Music. let's count the name column to find how many products there are per type. $row['type'] . // Print out result while($row = mysql_fetch_array($result)){ echo "There are ".sql file from our website. COUNT(name) FROM products GROUP BY type"." items. $result = mysql_query($query) or die(mysql_error()).73 MySQL COUNT . Toy. The "products" table that is displayed above has several products of various types. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row first.

MySQL Aggregate Functions . One use of SUM might be to find the total of all the items' price for each product type. . There are 1 Food items. We will be using the "products" table again -. Here's a visual of the "products" table.this time to display the use of MySQL's SUM function.73 MySQL SUM . The "products" table that is displayed above has several products of various types. we are going to apply the aggregate function to price and GROUP BY type to create four groups: Music. If you haven't already read through Tizag's Aggregate Introduction Lesson.95 32.99 3.SUM() This lesson will teach you how to use the aggregate function SUM(). Clothing and Food.?> Display: There are 2 Clothing items.sql file from our website. It explains concepts used in this lesson. please check it out now.97 3.50 34. You can download the products.99 89.99 21. There are 2 Toy items. Toy. Products Table: id 123451 123452 123453 123454 123455 123456 123457 123458 name Park's Great Hits Silly Puddy Playstation Men's T-Shirt Blouse Electronica 2002 Country Tunes Watermelon type Music Toy Toy Clothing Clothing Music Music Food price 19.Totaling Groups SUM is an aggregate function that totals a specific column for a group.55 8. Just as we did in the aggregate introduction lesson. There are 3 Music items. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row.

please check it out now. The table we will be using is "products" and you can download the products. It explains the meaning of aggregates and describes the GROUP BY statement. SUM(price) FROM products GROUP BY type". If you are new to MySQL/PHP programming you will need to know how to Create a MySQL Table and Insert a MySQL Row.99 .73 Total Music = $45. $result = mysql_query($query) or die(mysql_error()).AVG() This lesson will teach you how to use the aggregate function AVG(). $row['type']. Products Table: id 123451 123452 name Park's Great Hits Silly Puddy type Music Toy price 19. " = $". } ?> Display: Total Clothing = $67.94 MySQL Aggregate Functions . If you missed the Aggregate Introduction Lesson. echo "<br />". $row['SUM(price)']. The table can be entered through you MySQL interface or through PHP.47 Total Food = $8.99 3. // Print out result while($row = mysql_fetch_array($result)){ echo "Total ".sql file so you can follow along.53 Total Toy = $93.PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT type.

Our imaginary customers have been complaining recently that our prices are too high. Clothing and Food. } ?> Display: The average price of Clothing is $33. // Print out result while($row = mysql_fetch_array($result)){ echo "The average price of ". " is $". echo "<br />". PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT type. To find out this metric we are going to apply the aggregate function to the price and GROUP BY type to create four price groups: Music.95 32.99 21. $result = mysql_query($query) or die(mysql_error()).$row['AVG(price)'].735000 . $row['type'].55 8.50 34.Finding a Middle Ground The AVG function returns the average value for the specified column of a group. AVG(price) FROM products GROUP BY type". so we would like to find out the average price of each product type to see if this is in fact the truth.73 MySQL Average . Toy.97 3.123453 123454 123455 123456 123457 123458 Playstation Men's T-Shirt Blouse Electronica 2002 Country Tunes Watermelon Toy Clothing Clothing Music Music Food 89.

97 3. I think our imaginary customers should change their view and keep buying products from us.73 .sql. price.176667 The average price of Toy is $46. check out our Create a MySQL Table and Insert a MySQL Row lessons. If you missed the Aggregate Introduction Lesson. PHP and MySQL Code: <?php // Make a MySQL Connection name Park's Great Hits Silly Puddy Playstation Men's T-Shirt Blouse Electronica 2002 Country Tunes Watermelon type Music Toy Toy Clothing Clothing Music Music Food price 19. if you would like to create the table with PHP/MySQL. Clothing and Food. products. MySQL Aggregate Functions .99 21.730000 The average price of Music is $15. from our website. in my opinion.95 32. you might want to check it out to learn about the GROUP BY statement and its use with MySQL aggregate functions. However. we are going to GROUP BY type to create four groups: Music.99 89. A SQL file can be run through your MySQL administrator interface to create the table.55 8. Products Table: id 123451 123452 123453 123454 123455 123456 123457 123458 MySQL MIN The MIN function is an aggregate function that finds the smallest value in a group. Toy.50 34. You can download the table used in this example. The products table that is displayed above has several products of various types. of course.The average price of Food is $8. The column that will have the MIN function applied to it is.970000 Those prices seem very reasonable.MIN() This lesson will teach you how to use the aggregate function MIN(). Just as we did in the Aggregate Introduction Lesson.99 3. One use of MIN might be to find out the cheapest item in each group.

99 3. Below is the MySQL table "products".99 21.99 MySQL Aggregate Functions . MIN(price) FROM products GROUP BY type". " is $" . } ?> Display: The cheapest Clothing is $32.97 3.73 The cheapest Music is $3. as it explains many concepts used in this lesson! You can download the example the products.55 .99 89.95 32. // Print out result Cho "The cheapest ". echo "<br />".sql file from our website. which contains the SQL for the table below. please check it out now. $row['type'].50 34.50 The cheapest Food is $8.MAX() This lesson will teach you how to use the MAX() aggregate function .99 The cheapest Toy is $3. Products Table: id 123451 123452 123453 123454 123455 123456 123457 name Park's Great Hits Silly Puddy Playstation Men's T-Shirt Blouse Electronica 2002 Country Tunes type Music Toy Toy Clothing Clothing Music Music price 19. If you missed the Aggregate Introduction Lesson.$row['MIN(price)']. then you will need to know how to Create a MySQL Table and Insert a MySQL Row. $result = mysql_query($query) or die(mysql_error()). If you would like to use PHP/MySQL to create the table.$query = "SELECT type.

$row['type']. Clothing and Food. } ?> Display: The most expensive Clothing is $34.$row['MAX(price)']. The "products" table that is displayed above has several products of various types. We will also be applying the aggregate function to the price column. MAX(price) FROM products GROUP BY type".Finding the Big One MySQL's MAX aggregate function will find the largest value in a group. Just as we did in the aggregate introduction lesson.95 MySQL and SQL Injection If you take user input through a webpage and insert it into a MySQL database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. // Print out result while($row = mysql_fetch_array($result)){ echo "The most expensive ".123458 Watermelon Food 8.97 The most expensive Food is $8.73 MySQL MAX . Toy. echo "<br />".55 The most expensive Toy is $89. $result = mysql_query($query) or die(mysql_error()).73 The most expensive Music is $21. . PHP and MySQL Code: <?php // Make a MySQL Connection $query = "SELECT type. we are going to GROUP BY type to create four groups: Music. We could use the MAX function to find the most expensive item for each type of product. This lesson will teach you how to help prevent this from happening and help you secure your scripts and MySQL statements. " is $" .

such as SQLite and PostgreSQL. like their name. } To demonstrate the problem. executing all of the queries provided in one string and creating a serious security problem. The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. $matches)) { $result = mysql_query("SELECT * FROM users WHERE username=$matches[0]"). happily perform stacked queries. the mysql_query() function does not permit query stacking. $name would only contain alphanumeric characters and perhaps spaces. DELETE FROM users. other PHP database extensions. Fortunately. $_GET['username']. as a rule. If you try to stack queries. if (preg_match("/^\w{8. In the example below. } else { echo "username not accepted".20}$/".". However. by appending an entirely new query to $name. the call to the database turns into disaster: the injected DELETE query removes all records from users. such as the string ilia. Under normal circumstances. or executing multiple queries in a single function call. the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars modify these rules as needed. if you use MySQL. the call fails. Never trust user provided data. But here.Injection usually occurs when you ask a user for input. this is done by pattern matching. mysql_query("SELECT * FROM users WHERE name='{$name}'"). Preventing SQL Injection: if (get_magic_quotes_gpc()) . and instead of a name they give you a MySQL statement that you will unknowingly run on your database. process this data only after validation. consider this excerpt: // supposed input $name = "Qadir'.

the following acronyms are used in this lesson: Y . and give an INSERT example of each. We have assembled a "date playground" MySQL table that can be used to follow along with this lesson. a custom escaping mechanism must convert usersupplied % and _ characters to literals. } $name = mysql_real_escape_string($name).{ $name = stripslashes($name). dateplayground.com These date types are chosen for a column when you create a new table in MySQL. and YEAR. note the lower case . "%_").sql.hour segment m . This lesson will show you the proper formats of each type. Use addcslashes(). show their related MySQL functions. a function that let's you specify a character range to escape. mysql_query("SELECT * FROM users WHERE name='{$name}'"). MySQL Date . DATE. The LIKE Quandary: To address the LIKE quandary. try to create a new MySQL table with the date types we mentioned above. If you haven't already.year segment M . Often the most difficult part of using dates in MySQL is to be sure the format of the date you are trying to store matches the format of your table's date column. Also. Advertise on Tizag.month segment D .Formats MySQL comes with several data types for storing a date in its database system: DATETIME.minute segment. $sub = addcslashes(mysql_real_escape_string("%something_"). TIMESTAMP. // $sub == \%something\_ mysql_query("SELECT * FROM messages WHERE subject LIKE '{$sub}%'").day segment H .

'2020-2-14')". even though it provides a lot more information . mysql_query($query_auto) or die(mysql_error()). mysql_query($query_manual) or die(mysql_error()). Below is the proper format of a DATE. dp_date) VALUE ('DATE: Auto CURDATE()'. If you need to store years outside that range then use DATE instead of YEAR. but it won't be storing them as you expect. one manually and one using CURDATE(). dp_date) VALUES ('DATE: Manual Date'. PHP & MySQL Code: <?php //This assumes you have already created the 'dateplayground' table //Connect to DB $query_manual = "INSERT INTO dateplayground (dp_name. MySQL also has a date type just for that. $query_auto = "INSERT INTO dateplayground (dp_name.S . CURDATE() )". YEAR's format is simply: YYYY Date Range: 1901 to 2155 It should be noted that the range of years thatcan be stored are from 1901 to 2155. YYYY-MM-DD Date Range: 1000-01-01 to 9999-12-31 If you try to enter a date in a format other than the Year-Month-Day format then it might work. We have used CURDATE() again.YEAR If you just need to store the year of an event. Below we have created 2 dates. To insert the current date into your table you can use MySQL's built-in function CURDATE() in your query. ?> MySQL Date .sec segment MySQL Date – DATE The default way to store a date in MySQL is with the type DATE. Below we have created another manual and automatic example to show off YEAR's use.

besides the year. CURDATE() )". CURDATE() )". .DATETIME DATETIME actually stores both the current date and time. is just ignored by YEAR. dp_datetime) VALUE ('DATETIME: Auto CURDATE()'. $query_auto = "INSERT INTO dateplayground (dp_name. month.than YEAR requires. PHP & MySQL Code: <?php $query_manual = "INSERT INTO dateplayground (dp_name. PHP & MySQL Code: <?php $query_manual = "INSERT INTO dateplayground (dp_name. mysql_query($query_manual) or die(mysql_error()). All the date information. DATETIME's format is: YYYY-MM-DD HH:mm:SS Date Range: 1000-01-01 00:00:00 to 9999-12-31 23:59:59 The hyphen and the colon are the standard character to separate a date and time respectively. With DATETIME you can choose to store the date or the time and date together. dp_year) VALUES ('YEAR: Manual Year'. minute. and NOW(). In our example below we have manually stored a complete DATETIME and also used three different MySQL functions: CURDATE(). meaning it has the ability to store the year. mysql_query($query_auto) or die(mysql_error()). but MySQL allows for you to choose your own delimiters if you wish. and second inside it. day. '2011')". '1776-7-4 04:13:54')". CURTIME(). ?> MySQL Date . dp_year) VALUE ('YEAR: Auto CURDATE()'. dp_datetime) VALUES ('DATETIME: Manual DateTime'. but you cannot store just the time. $query_autodate = "INSERT INTO dateplayground (dp_name. hour.

NOW() )". CURTIME() )". so you can see what happens when you enter a date that is outside the boundaries of a this type.$query_autotime = "INSERT INTO dateplayground (dp_name. dp_datetime) VALUE ('DATETIME: Auto NOW()'. dp_timestamp) VALUE ('TIMESTAMP: Auto CURDATE()'. dp_timestamp) VALUE ('TIMESTAMP: Auto CURTIME()'. $query_autodate = "INSERT INTO dateplayground (dp_name. mysql_query($query_autonow) or die(mysql_error()). mysql_query($query_autotime) or die(mysql_error()). If you want more versatility than this date type provides. ?> MySQL Date – TIMESTAMP TIMESTAMP is a format popularized by the *NIX operating systems that stores the amount of time that has passed since January 1. $query_autonow = "INSERT INTO dateplayground (dp_name. '1776-7-4 04:13:54')". CURDATE() )". CURTIME() )". dp_datetime) VALUE ('DATETIME: Auto CURTIME()'. remember to try DATETIME. 1970. PHP & MySQL Code: <?php //This will fail $query_manual = "INSERT INTO dateplayground (dp_name. YYYY-MM-DD HH:mm:SS Date Range: 1970-01-01 00:00:00 to 2037-12-31 23:59:59 The big difference between DATETIME and TIMESTAMP is the date ranges that can be stored. mysql_query($query_manual) or die(mysql_error()). mysql_query($query_autodate) or die(mysql_error()). dp_timestamp) VALUES ('TIMESTAMP: Manual Timestamp'. dp_timestamp) . //This will fail $query_autotime = "INSERT INTO dateplayground (dp_name. Below we have purposely entered an erroneous date. manually. //This will fail $query_autonow = "INSERT INTO dateplayground (dp_name.

mysql_field_name($result. $i++){ echo "<th>". mysql_query($query_autotime) or die(mysql_error()). } echo "</table>"."</th>". } echo "</tr>". for($i = 0. while($row = mysql_fetch_array($result)){ echo "<tr>". $i < mysql_num_fields($result). $i). $i++){ echo "<td>". mysql_query($query_autodate) or die(mysql_error()). mysql_query($query_manual) or die(mysql_error()). for($i = 0."</td>".VALUE ('TIMESTAMP: Auto NOW()'. ?> Viewing dateplayground in PHP Below is a quick script that will spit out the MySQL table dateplayground in HTML. mysql_query($query_autonow) or die(mysql_error()). $row[$i] . } echo "</tr>". PHP & MySQL Code: <?php $query = "SELECT * FROM dateplayground". echo "<table border='1'><tr>". $result = mysql_query($query) or die(mysql_error()). ?> . $i < mysql_num_fields($result). NOW() )".

sql.0000-00-00 00 00:00:00 0000-00. MySQL will often just enter in the default value of all zeros. MySQL Time – TIME First you need to create a MySQL table with a TIME type. TIMESTAMP: Manual Timestamp. . When you enter dates that are out of the range or in the wrong format for a given date type.0000-00-00 00 00:00:00 0000-00.2006-09-19 00 16:56:56 0000-00. DATETIME.0000-00-00 00 00:00:00 DATE: Auto CURDATE() 0000 YEAR: Manual Year 2011 YEAR: Auto CURDATE() 2006 DATETIME: Manual DateTime DATETIME: Auto CURDATE() DATETIME: Auto CURTIME() 0000 0000 0000 DATETIME: Auto NOW() 0000 TIMESTAMP: Manual Timestamp TIMESTAMP: Auto CURDATE() TIMESTAMP: Auto CURTIME() TIMESTAMP: Auto NOW() 0000 0000 0000 0000 Notice that the rows DATETIME: Auto CURTIME(). MySQL Time .sql Display: dp_name DATE: Manual Date dp_year dp_date 0000 dp_datetime dp_timestamp 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 0000-00-00 00:00:00 2006-09-19 00:00:00 0000-00-00 00:00:00 2006-09-19 16:56:56 2020-02. This is because they were the INSERTs that were erroneous.0000-00-00 19 00:00:00 0000-00.0000-00-00 00 00:00:00 0000-00.0000-00-00 00 00:00:00 0000-00.0000-00-00 14 00:00:00 2006-09. and TIMESTAMP.0000-00-00 00 00:00:00 0000-00.Formats There are three different types of time data types in MySQL: TIME. We have one already created if you want to use it: timeplayground. If you would like to learn more about DATETIME and TIMESTAMP. and TIMESTAMP: Auto CURTIME() have all zeros. then check out our MySQL Date section. This lesson will just be covering the basics of using TIME.2006-09-19 00 00:00:00 0000-00.Finished dateplayground. as we've covered them there.1776-07-04 00 04:13:54 0000-00.0000-00-00 00 00:00:00 0000-00.

mysql_query($query_manual2) or die(mysql_error()). Below we have entered 3 manual times into MySQL.NOW() To get the current time. use MySQL's built in function NOW().Hour. Standard format: HH:MM:SS Extended hour format: HHH:MM:SS Time Range: -838:59:50 to 838:59:59 When manually entering a time into MySQL it is highly recommended that you use the exact format show above. but they don't always behave as you would expect. dp_time) VALUES ('TIME: Manual Time'. PHP & MySQL Code: . M . mysql_query($query_manual3) or die(mysql_error()).The TIME data type can be used to store actual times as well as the amount of time between two points in time (like the time between now and the weekend) that may sometimes be larger than 23 hours. The first is done in the recommended format. // will this shorthand work? $query_manual3 = "INSERT INTO timeplayground (dp_name. MySQL allows for many different ways to enter a time. H . the second is a shorthand version of the first and the final example is outside the allowed time range. S . '12:10:00')". '978:31:12')". Using the standard/extended format we have shown above will help you avoid annoying problems. PHP & MySQL Code: <?php //This assumes you have already created the 'dateplayground' table //Connect to DB $query_manual1 = "INSERT INTO timeplayground (dp_name. dp_time) VALUES ('TIME: Manual Time'. '1210')". dp_time) VALUES ('TIME: Manual Time'.Second. ?> MySQL Time . but MySQL is smart enough to just use the data needed for TIME. //how about this? mysql_query($query_manual1) or die(mysql_error()).Minute. NOW() contains both the date and time information. //perfectly done $query_manual2 = "INSERT INTO timeplayground (dp_name.

mysql_field_name($result. $i < mysql_num_fields($result). for($i = 0. } echo "</table>". } echo "</tr>". $result = mysql_query($query) or die(mysql_error()). for($i = 0. $i < mysql_num_fields($result).<?php $query_auto = "INSERT INTO timeplayground (dp_name.sql table. mysql_query($query_auto) or die(mysql_error()). $i++){ echo "<td>". echo "<table border='1'><tr>". ?> MySQL timeplayground. } echo "</tr>". $i). PHP & MySQL Code: <?php $query = "SELECT * FROM timeplayground". while($row = mysql_fetch_array($result)){ echo "<tr>". $i++){ echo "<th>". $row[$i] ."</td>".sql Displayed Below is a small PHP script to spit out a rough version of our timeplayground."</th>". ?> . dp_time) VALUE ('TIME: Auto NOW()'. NOW() )".

Indexes are something extra that you can enable on your MySQL tables to increase performance. then you would need to create an index for employeeID. MySQL will build a lookup index where employeeID specific queries can be run quickly. inserting and removing entries in your table this could have a negative impact on performance. trying to push the limits of their hardware for maximum performance. MySQL Index . MySQL Index .Overclock Your Tables Hardware enthusiasts have been overclocking their PCs for years now. If you have a table with the columns: name.Overclock Your Tables Hardware enthusiasts have been overclocking their PCs for years now. This is why it's best to use the formats we've described at the beginning. MySQL interpreted 1210 as MM:SS instead of HH:MM as we assumed. birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries.sql Display: dp_name TIME: Manual Time TIME: Manual Time TIME: Manual Time TIME: Auto NOW() dp_time 12:10:00 00:12:10 838:59:59 14:30:36 Our first manual time was handled just fine. indexes in MySQL can increase the speed of your MySQL queries to squeeze a bit more performance out of your database.Finished timeplayground. This means that if you are constantly updating. However. while other times they push a little too hard and end up damaging the computer! Although it isn't quite as extreme. Sometimes they are successful and their applications run speedy fast. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table.Speed and Extra Overhead Indexes are created on a per column basis. so that it would be within TIME's range. trying to push the limits of their hardware for maximum performance.cbut they do have some downsides. while other times they push a little too hard and end up damaging the computer! Although it isn't quite as extreme. The third manual entry was changed from 978:31:12 to 838:59:59. age. Sometimes they are successful and their applications run speedy fast. MySQL Index . indexes in MySQL can increase the speed of your MySQL queries to squeeze a bit more performance out of your database. age and birthday queries would not be any faster. but our second one did not. the name. . When you create this index.

When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries. INDEX (employeeID) ) Creating a MySQL Index . If you have a table with the columns: name. We have created two fields: name and employeeID (index). MySQL Code: CREATE TABLE employee_records2 (name VARCHAR(50). . age.Speed and Extra Overhead Indexes are created on a per column basis. the name.MySQL Index . First.cbut they do have some downsides. MySQL will build a lookup index where employeeID specific queries can be run quickly. MySQL Code: CREATE TABLE employee_records ( name VARCHAR(50). inserting and removing entries in your table this could have a negative impact on performance. age and birthday queries would not be any faster.New Table If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below.Existing Table You can also add an index to an older table that you think would benefit from some indexing. MySQL Code: CREATE INDEX id_index ON employee_records2(employeeID) We keep our existing employeeID field and create a new index id_index that is made up of employeeID data. Indexes are something extra that you can enable on your MySQL tables to increase performance. employeeID INT) With our newly created table we are going to update the "employee_records2" table to include an index. However. then you would need to create an index for employeeID. The syntax is very similar to creating an index in a new table. This means that if you are constantly updating. Creating a MySQL Index . let's create the table. When you create this index. employeeID INT.

A complete resource for PHP stuff. MySQL Useful Resources MySQL and PERL .A small article on MySQL. MySQL Code: CREATE TABLE employee_records2 (name VARCHAR(50). MySQL Reference Manual . get the MySQL news update.A complete official reference for MySQL. let's create the table. Starting from latest PHP updates to latest function manual is available at this site. We have created two fields: name and employeeID (index). worth to go through it.If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below. MySQL at Wikipedia . employeeID INT.Its a tutorial from Tutorials Point which explains you how to use MySQL along with PERL and DBI module. MySQL Code: CREATE INDEX id_index ON employee_records2(employeeID) We keep our existing employeeID field and create a new index id_index that is made up of employeeID data. MySQL Official Website . The syntax is very similar to creating an index in a new table.Existing Table You can also add an index to an older table that you think would benefit from some indexing. The mailing list is also a great resources for anyone who want to build dynamic websites using MySQL. . First. INDEX (employeeID) ) Creating a MySQL Index . Here you will learn all the required MySQL operations alongwith examples. PHP Official Website: . employeeID INT) With our newly created table we are going to update the "employee_records2" table to include an index. MySQL Code: CREATE TABLE employee_records ( name VARCHAR(50).Here you can download the latest MySQL release.

Primary Key: A primary key is unique. RDBMS Terminology: Before we proceed to explain MySQL database system. A table in a database looks like a simple sColumn: One column (data element) contains data of one and the same kind. and replicating the data it holds. you can redistribute it and/or modify it under the terms of the GNU General Public License. entry or record) is a group of related data. for example the column postcode. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. Row: A row (= tuple. managing. So now a days we use relational database management systems (RDBMS) to store and manager huge volume of data. Each database has one or more distinct APIs for creating. accessing. columns. is a mature. such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those type of systems.MySQL-sr-lib . powerful. This is a A repository of ready to use routines for everyday needs. the Structured Query Language. Interprets an SQL query and combines information from various tables.MySQL General Purpose Stored Routines Library. and versatile relational query language. Table: A table is a matrix with data.If you are new to SQL then go through this tutorial to understand SQL basics. Other kinds of data stores can be used. This program is free software. Database: A database is a collection of tables. lets revise few definitions related to database. Updates the indexes automatically. MySQL Database Introduction What is Database? A database is a separate application that stores a collection of data. . A Relational DataBase Management System (RDBMS) is a software that: Enables you to implement a database with tables. searching. for example the data of one subscription. Guarantees the Referential Integrity between rows of various tables. A key value can not occur twice in one table. and indexes. Understanding SQL . with related data. redundantly to make the system faster. Redundancy: Storing data twice. SQL.

MySQL Database: MySQL is a fast. MySQL works on many operating systems and with many languages including PHP. MySQL AB makes the following RPMs available for download on its web site: . Compound Key: A compound key (composite key) is a key that consists of multiple columns. C++. C. MySQL is developed.Linux and Windows Downloading MySQL: All downloads for MySQL are located at MySQL Downloads. So you have nothing to pay to use it. MySQL is becoming so popular because of many good reasons. up to 50 million rows or more in a table. because one column is not sufficiently unique. MySQL Installation . the platform you want. Installing MySQL on Linux/Unix The recommended way to install MySQL on a Linux system is via RPM. MySQL is released under an open-source license. MySQL is very friendly to PHP. which is a Swedish company. Index: An index in a database resembles an index at the back of a book. Foreign Key: A foreign key is the linking pin between two tables. MySQL is a very powerful program in its own right. as exactly as possible. MySQL uses a standard form of the well-known SQL data language. the most appriciated language for web development.With a key you can find at most one row. Pick the version number you want and. but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB). marketed. PERL. Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an existing row. It handles a large subset of the functionality of the most expensive and powerful database packages. and supported by MySQL AB. JAVA etc. easy-to-use RDBMS used being used for many small and big businesses. The open source GPL license allows programmers to modify the MySQL software to fit their own specific environments. MySQL works very quickly and works well even with large data sets. MySQL is customizable. The default file size limit for a table is 4GB. MySQL supports large databases.

controls user access.rpm [root@host]# rpm -i MySQL-shared-5.Switch to the directory containing the RPMs: [root@host]# rpm -i MySQL-5. which manages databases and tables.MySQL client programs. Simply download the installer package. which makes it possible to connect to.9-0.Benchmark and performance testing tools for the MySQL database server.0. Now follow the following steps to proceed for installation: Login to the system using root user.0. and interact with. and processes SQL queries.ll usually work on other Linux variants with no difficulty. The MySQL RPMs listed here are all built on a SuSE Linux system. MySQL-devel . Remember to replace the filename in italics with the file name of your RPM.i386.i386. creating necessary configuration and starting MySQL server automatically. but they.i386.exe. Default installer setup.rpm [root@host]# rpm -i MySQL-bench-5.rpm [root@host]# rpm -i MySQL-devel-5. You can find all the MySQL related binaries in /usr/bin and /usr/sbin.Shared libraries for the MySQL client MySQL-bench . ? This is optional but recommended step to install the remaining RPMs in the same manner: [root@host]# rpm -i MySQL-client-5. unzip it anywhere. as MySQL now comes neatly packaged with an installer.0. MySQL-client .rpm ? Above command takes care of installing MySQL server.9-0.9-0.The MySQL database server.9-0.exe will walk you through the trivial process and by default will install everything under C:\mysql.MySQL . MySQL-shared .0. .i386. creating a user of MySQL.9-0. the server.0.rpm Installing MySQL on Windows: Default installation on any version of Windows is now much easier than it used to be.i386.Libraries and header files that come in handy when compiling other programs that use MySQL. Install the MySQL database server by executing the following command. and run setup. All the tables and databases will be created in /var/lib/mysql directory.

you should remember to halt the process by hand by using mysqladmin. MySQL Administration Running and Shutting down MySQL Server: First check if your MySQL server is running or not. and the server has been started.Test the server by firing it up from the command prompt the first time. you may have a permissions issue. Verifying MySQL Installation: After MySQL has been successfully installed. you can verify that all is working as it should via some simple tests.exe If all went well. Make sure that the directory that holds your data is accessible to whatever user (probably mysql) the database processes run under.exe --console NOTE: If you are on NT then you will have to use mysqld-nt. MySQL will not add itself to the start menu.exe instead of mysqld. you will see some messages about startup and InnoDB. If server is not running then you can start it by using following command: root@hoat# cd /usr/bin . Go to the location of the mysqld server. Therefore. the base tables have been initialized. You can use following command to check this: ps -ef | grep mysqld If your MySql is running then you will see mysqld process listed out in your result. Task Manager. Task List. This binary would be available in /usr/bin on linux and in C:\mysql\bin on windows./mysqladmin -u root -p shutdown ./safe_mysqld & Now if you want to shutdown an already running MySQL server then you can do it by using following command: root@hoat# cd /usr/bin . and there is no particularly nice GUI way to stop the server either. or other Windows-specific means. Use the mysqladmin Utility to Obtain Server Status: Use mysqladmin binary to check server version. which is probably C:\mysql\bin. if you tend to start the server by double clicking the mysqld executable. and type: mysqld. If not.

1 row affected (0. Below is an example of adding new user guest with SELECT. PASSWORD('guest123'). select_priv. password. As you can see in the above example the password mypass is encrypted to 6f8c114b58f2ce9e. 'Y'.00 sec) When adding a new user remember to encrypt the new password using PASSWORD() function provided by MySQL. INSERT and UPDATE privileges with the password guest123 the SQL query is : root@host# mysql -u root –p Enter password:******* mysql> use mysql. 'Y'). host | user | password | | localhost | guest | 6f8c114b58f2ce9e | 1 row in set (0. 1 row affected (0. Query OK. . Database changed mysql> INSERT INTO user (host.20 sec) mysql> FLUSH PRIVILEGES.01 sec) mysql> SELECT host. If you don't use it then you won't be able to connect to mysql using the new user account at least until the server is rebooted. Query OK. insert_priv. password FROM user WHERE user = 'guest'. update_priv) VALUES ('localhost'. Notice the FLUSH PRIVILEGES statement. 'guest'.Enter password: ****** Setting Up a MySQL User Accounts: For adding a new user to MySQL you just need to add a new entry to user table in database mysql. user. 'Y'. user. This tells the server to reload the grant tables.

DELETE.* -> TO 'zara'@'localhost' -> IDENTIFIED BY 'zara123'. Select_priv Insert_priv Update_priv Delete_priv Create_priv Drop_priv Reload_priv Shutdown_priv Process_priv File_priv Grant_priv References_priv Index_priv Alter_priv Another way of adding user account is by using GRANT SQL command. . Enter password:******* mysql> use mysql. root@host# mysql -u root -p password.You can also specify other privileges to a new user by setting the values of following columns in user table to 'Y' when executing the INSERT query or you can update them later using UPDATE query. Database changed mysql> GRANT SELECT.DROP -> ON TUTORIALS.UPDATE.INSERT.CREATE. Following example will ada user zara with password zara123 for a particular database called TUTORIALS.

. defaults.server] user=mysql basedir=/var/lib [safe_mysqld] err-log=/var/log/mysqld. types of attributes. and other information for a table. key information.sock [mysql. By default it will have following entries: [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql. whether NULL is permitted. SHOW TABLES: Shows the tables in the database once a database has been selected with the use command. including the PRIMARY KEY. SHOW DATABASES: Lists the databases that are accessible by the MySQL DBMS. SHOW COLUMNS FROM tablename: Shows the attributes.pid Here you can specify a different directory for error log. SHOW TABLE STATUS LIKE tablename\G: Reports details of the MySQL DBMS performance and statistics. SHOW INDEX FROM tablename: Presents the details of all indexes on the table.This will also create an entry in mysql database table called user. Administrative MySQL Command: Here is the list of important MySQL command which you will use time to time to work with MySQL database: USE Databasename : This will be used to select a particular database in MySQL workarea. The /etc/my. NOTE: MySQL does not terminate a command until you give a semi colon (.) at the end of SQL command.cnf File Configuration: Most of the cases you should not touch this file. otherwise you should not change any entry in this table.log pid-file=/var/run/mysqld/mysqld.

...]).. usually a word that describes what the function does. The following are two of the functions which we will use in our tutorial mysqli_connect($connect).. if( !$retval ) { die ( "Error: a related error message" ). PHP provides various functions to access MySQL database and to manipulate data records inside MySQL database. } // Otherwise MySQL or PHP Statements ?> .. The PHP functions for use with MySQL have the following general format: mysql_function(value. Following example shows a generic sysntax of PHP to call any MySQL function. C. This tutorial focuses heavily on using MySQL in a PHP environment.value. PHP is the most popular one because of its web application development capabilities. The second part of the function name is specific to the function. JAVA and PHP. If you are interested in MySQL with PERL then you can look into PERL and MySQL Tutorial.). C++. You would require to call PHP functions in the same way you call any other PHP function. <html> <head> <title>PHP with MySQL</title> </head> <body> <?php $retval = mysql_function(value. Out of these languages."SQL statement"). mysqli_query($connect.MySQL PHP Syntax MySQL works very well in combination of various programming languages like PERL. [value.

You can disconnect from MySQL database any time using exit command at mysql> prompt.9 Type 'help. Your MySQL connection id is 2854760 to server version: 5.The username .passwd.</body> </html> Starting from next chapter we will see all the important MySQL functionality along with PHP. user Optional . MySQL Database Connection MySQL Connection using mysql binary: You can establish MySQL database using mysql binary at command prompt.user.client_flag).The host name running database server.new_link. or \g. mysql> exit Bye MySQL Connection using PHP Script: PHP provides mysql_connect() function to open a database connection. Syntax: connection mysql_connect(server. Example: Here is a simple example to connect to MySQL server from command prompt: [root@host]# mysql -u root –p Enter password:****** This will give you mysql> command prompt where you will be able to execute any SQL command. or FALSE on failure. In above example we have used root as a user but you can use any other user. Following is the result of above command: Welcome to the MySQL monitor.0. If not specified then default value is localhost:3036. This function takes five parameters and returns a MySQL link identifier on success. Parameter Description server Optional .' or '\h' for help. Any user will be able to perform all the SQL operation which are allowed to that user. Type '\c' to clear the buffer. Commands end with .

A combination of the following constants: MYSQL_CLIENT_SSL .accessing the database. new_link Optional .Use compression protocol Optional .Use SSL encryption MYSQL_CLIENT_COMPRESS . $dbuser = 'guest'.A combination of the following constants: Allow space after function names MYSQL_CLIENT_INTERACTIVE . If not specified then default is the name of the user that owns the server process.If a second call is made to mysql_connect() with the same arguments. $dbuser. client_flags Optional . Syntax: Bool mysql(resource $link_identifire). $dbpass). This function returns true if it closes connection successfully otherwise it returns false. no new connection will be established. If not specified then default is an empty password. Example: Try out following example to connect to a MySQL server: <html> <head> <title>Connecting MySQL Server</title> </head> <body> <?php $dbhost = 'localhost:3036'. the identifier of the already opened connection will be returned. passwd Optional . . instead. This function takes a single parameter which is a connection returned by mysql_connect() function. $dbpass = 'guest123'. $conn = mysql_connect($dbhost.The password of the user accessing the database.Allow interactive timeout seconds of iYou can disconnect from MySQL database anytime using another PHP function mysql_close(). If a resource is not specified then last opened database is closed.

if(! $conn ) { die('Could not connect: ' . mysql_close($conn). mysql_error()). and packing the strength and experience of PHP users into a nicely organised OOP library. This repository is bringing higher level programming to PHP.What Is a Session? A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.There is only one session object available to your PHP scripts at any time. PHP is basically used for developing web based software applications. PEAR also provides a command-line interface that can be used to automatically install “packages” Answer2: PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard. } echo 'Connected successfully'.What is meant by PEAR in php? Answer1: PEAR is the next revolution in PHP. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor. The purpose of PEAR is to provide: A structured library of open-sourced code for PHP users A system for code distribution and package maintenance A standard style for code written in PHP . ?> </body> </html> What’s PHP ? The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases.

What is the difference between $message and $$message? Anwser 1: $message is a simple variable whereas $$message is a reference variable.How can we know the number of days between two given dates using PHP? Simple arithmetic: $date1 = date(‘Y-m-d’). Example: $user = ‘bob’ is equivalent to $holder = ‘user’. The PHP Extension Community Library (PECL). A web site. $date2 = ’2006-07-01′. echo “Number of days since ’2006-07-01′: $days”. MySQL will do a repair of only the index tree.The PHP Foundation Classes (PFC). The project has been founded by Stig S. .How can we repair a MySQL table? The syntex for repairing a mysql table is: REPAIR TABLE tablename REPAIR TABLE tablename QUICK REPAIR TABLE tablename EXTENDED This command will repair the table specified. If EXTENDED is given. Bakken in 1999 and quite a lot of people have joined the project since then. mailing lists and download mirrors to support the PHP/PEAR community PEAR is a community-driven project with the PEAR Group as the governing body. If QUICK is given. $days = (strtotime() – strtotime()) / (60 * 60 * 24). it will create index row by row.

$$holder = ‘bob’;Anwser 2: They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.What Is a Persistent Cookie? A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences: *Temporary cookies can not be used for tracking long-term information. *Persistent cookies can be used for tracking long-term information. *Temporary cookies are safer because no programs other than the browser can access them. *Persistent cookies are less secure because users can open cookie files see the cookie values.What does a special set of tags <?= and ?> do in PHP? The output is displayed directly to the browser.How do you define a constant? Via define() directive, like define (“MYCONSTANT”, 100);What are the differences between require and include, include_once? Anwser 1: require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.But require() and include() will do it as many times they are asked to do. Anwser 2: The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors. Anwser 3: All three are used to an include file into the current page. If the file is not present, require(), calls a fatal error, while in include() does not.

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists. Anwser 4: File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.What is meant by urlencode and urldecode? Anwser 1: urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(“10.00%”) will return “10%2E00%25″. URL encoded strings are safe to be used as part of URLs. urldecode() returns the URL decoded version of the given string.Anwser 2: string urlencode(str) – Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version: Alphanumeric characters are maintained as is. Space characters are converted to “+” characters. Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character. string urldecode(str) – Returns the original string of the input URL encoded string.For example: $discount =”10.00%”; $url = “http://domain.com/submit.php?disc=”.urlencode($discount); echo $url;You will get “http://domain.com/submit.php?disc=10%2E00%25″.How To Get the Uploaded File Information in the Receiving Script? Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through

the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a twodimensional array as: $_FILES[$fieldName]['name'] – The Original file name on the browser system. $_FILES[$fieldName]['type'] – The file type determined by the browser. $_FILES[$fieldName]['size'] – The Number of bytes of the file content. $_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server. $_FILES[$fieldName]['error'] – The error code associated with this file upload. The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.What is the difference between mysql_fetch_object and mysql_fetch_array? MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an arrayHow can I execute a PHP script using command line? Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program. Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example? In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10))? Total 5 types of tables we can create 1. MyISAM2. Heap 3. Merge

if (mysql_query($sql.\n”). ?> . you can run the CREATE TABLE statement as shown in the following sample script: <?php include “mysql_connection. “)”. INNO DB 5. } mysql_close($con). $sql = “CREATE TABLE Tech_links (“ .\n”). $con)) { print(“Table Tech_links created. ” id INTEGER NOT NULL” .php”.4. time TIMESTAMP DEFAULT sysdate()” . counts INTEGER” .How To Create a Table? If you want to create a table. When you fire the above create query MySQL will create a MyISAM table. “.23. ISAM MyISAM is the default storage engine as of MySQL 3. } else { print(“Table creation failed. notes VARCHAR(1024)” . “. url VARCHAR(80) NOT NULL” . “. “.

}What is the functionality of the function strstr and stristr? . location=”mailto:mailid@domain. But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example: function myfunction(form) { tdata=document. …).com?subject=…”. This function is case-sensitive.When are you supposed to use endif to end the conditional statement? When the original if was followed by : and then the code block without braces.Remember that mysql_query() returns TRUE/FALSE on CREATE statements.How can we send mail using JavaScript? No. stristr() is idential to strstr() except that it is case insensitive. For example. INSERT into user (password.tbox1. put an ampersand in front of it. Answer2 You can use the MySQL PASSWORD() function to encrypt username and password. return true.How do you pass a variable by value? Just like in C++.value. If you run this script. like $a = &$bWhat is the functionality of the functions STRSTR() and STRISTR()? string strstr ( string haystack.How can we encrypt the username and password using PHP? Answer1 You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Password”). string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. …) VALUES (PASSWORD($password”)). There is no way to send emails directly using JavaScript. you will get something like this: Table Tech_links created.myform.

strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. $comment = ‘I want to say: “It\’s a good site! :->”‘. print(“<p>” .What is the difference between ereg_replace() and eregi_replace()? eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.How do I find out the number of parameters passed into function9.” to submit comments about TECHPreparation.frm’ file stores the table definition.php?name=Guest&comment=$comment\”>” . The data file has a ‘. ? func_num_args() function returns the number of parameters passed in.com”.How To Protect Special Characters in Query String? If you want to include special characters like spaces in the query string. For example: strstr(“user@example. you need to protect them by applying the urlencode() translation function. print(“<p>Please click the links below” .com:</p>”). The index file has a ‘. stristr() is idential to strstr() except that it is case insensitive. and myi? What these files contain? In MySQL. the default table type is MyISAM.com”.If the variable $a is equal to 5 and variable $b is equal to character a. it’s a reference to existing variable. The ‘.MYI’ (MYIndex) extension.”@”) will return “@example. The script below shows how to use urlencode(): <?php print(“<html>”).”<a href=\”processing_forms.MYD’ (MYData) extension. what’s the value of $$b? 100. myd.What is the purpose of the following files having extensions: frm. Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. $comment = urlencode($comment).

’<a href=”processing_forms. 3. such errors are not displayed to the user at all – although you can change this default behavior. while __wakeup retrieves them. but they do not result in script termination.How do you call a constructor for a parent class? parent::constructor($value)WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP? Here are three basic types of runtime errors in PHP: 1.$comment.’”>’ . By default. these variations are represented by twelve different error typesWhat’s the special meaning of __sleep and __wakeup? __sleep returns the array of all the variables than need to be saved..What are the differences between DROP a table and TRUNCATE a table? DROP TABLE table_name – This will delete the table and its data. . These errors cause the immediate termination of the script. instantiating an object of a non-existent class. Fatal errors: These are critical errors – for example. Notices: These are trivial. $comment = ‘This visitor said: “It\’s an average site! $comment = urlencode($comment). ?>Are objects passed by value or by reference? Everything is passed by value. TRUNCATE TABLE table_name – This will delete the data of the table. or calling a non-existent function. these errors are displayed to the user. Warnings: These are more serious errors – for example. Internally.”It’s an average site. and PHP’s default behavior is to display them to the user when they take place. accessing a variable that has not yet been defined.</a></p>”). print(“</html>”).php?’.How can we submit a form without a submit button? “‘. By default. attempting to include() a file which does not exist. non-critical errors that PHP encounters while executing a script – for example. 2.”It’s an excellent site!</a></p>”). but not the table definition. print(“<p>” .

*)$/” as the regular expression pattern. For example: <a href=”javascript: document. But for long data sending.” .Would you initialize your strings with single quotes or double quotes? Since the data inside the single-quoted string is not parsed for variable substitution.com”. For example: preg_match(“/. there.\nHow are you?\nThanks for visiting techpreparation’.*)$/”. which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Once most important difference is when you are sending the form with GET method. then you can use GET” Method.If you don’t want to use the Submit button to submit a form. give the case where we can use GET and we can use POST methods? Anwser 1: When we submit a form. it’s always a better idea speed-wise to initialize a string with single quotes. Anwser 2: When you want to send short or small data. Whereas if you send the form with POST” method then user can not see that information. the data is sent as “standard input.submit(). But you need to use some JavaScript code in the URL of the link.*@(. say more then 100 character you can use POST method.myform. just as a sequence of two characters – \ and n. print $str.”http://info@abc. not containing ASCII characters.com using regular expression of php? We can use the preg_match() function with “/. Post method doesn’t display these values.*@(.$data). the browser appends the data onto the URL. ?> Because inside the single quotes the \n character is not interpreted as newline. With the Post method. echo $data[1].”>Submit Me</a> Why doesn’t the following code print the newline properly? <?php $str = ‘Hello.How can we extract string ‘abc. you can use normal hyper links to submit a form. Anwser 3: What are “GET” and “POST”? GET and POST are methods used to send data to the server: With the GET method.What are the differences between GET and POST methods in form submitting.com ‘ from a string http://info@abc. You can see the output which you are sending in the address bar. unless you specifically need variable substitution.

With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn’t display value with URL. when we do submit or similar action. Anwser 4: In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar./login.php) and is retrieved by login. Ex: Assume we are logging in with username and password. in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string. Not advisable if you are sending login info like password etc.php by $_POST['username'] and $_POST['password'].php.php?username=…&password=… as URL when executing the script login. Anwser 6: On the server side.php. . The $_POST array stores data submitted by the POST method.Major Difference In simple words. the main difference between GET and POST is where the submitted is stored. POST: we are submitting a form to login. values are sent through invisible standard input (notice . In the post method the data will be available as data blocks and not as query string in case of get method. values are sent through visible query string (notice . POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string).php) and is retrieved by login. which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. when we do submit or similar action. Anwser 5: When we submit a form. It passes value in the form of Object and we can submit large data from the form. GET: we are submitting a form to login./login. The $_GET array stores data submitted by the GET method.php by $_GET['username'] and $_GET['password'].

print and printf.form.What is the difference between characters 23 and \x23? The first one is octal 23. we can call the document.php”) two times in a php page “makeit.How many ways we can retrieve the date in result set of mysql using php? As individual objects so single record or as a set or arrays.How come the code works.What is the difference between the functions unlink and unset? unlink() is a function for file system handling.With a heredoc syntax. and just outputs the contents following the construct to the screen. do I get variable substitution inside the heredoc contents? Yes.submit() function to submit the form. It will simply delete the file in context. but doesn’t for two-dimensional array of mine? Any time you have an array with more than one dimension. but it returns TRUE on successful output and FALSE if it was unable to print out the string. but usually the speed advantage is negligible. the difference is that data submitted by the GET method will be displayed in the browser’s address field. For example: <input type=button value=”Save” onClick=”document. ‘to’.Can we use include (“abc.How can we submit form without a submit button? We can use a simple JavaScript code linked to an event trigger of any form field. and might not be there for future versions of PHP.How can we register the variables into a session? session_register($session_var). but it’s the slowest way to print out data out of echo. like: <?php echo ‘Welcome ‘. GET method is mostly used for submitting a small amount and less sensitive data. printf is a function. the second is hex 23.I am writing an application in PHP that outputs a printable version of . echo is the most primitive of them. not a construct. ‘ ‘. Data submitted by the POST method will not be displayed anywhere on the browser. However. print “Contents: {$arr[1][2]}” would’ve worked. It is also generally argued that echo is faster. unset() is a function for variable management. ?> and it will output the string “Welcome to techpreparations!” print does not take multiple parameters. and allows such advantages as formatted output.For printing out strings. $_SESSION['var'] = ‘value’. Explain the differences.form.php”? Yes.On the browser side. ‘techpreparations!’. In the JavaScript code. It will make a variable undefined. POST method is mostly used for submitting a large amount or sensitive data. print and printf. complex parsing syntax is required. there are echo. you can pass multiple parameters to echo. print is also a construct (so parentheses are optional when calling it).submit()”>How can we create a database using PHP and mysql? We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

*@([^?]*)|’. ucwords() makes every first letter of every word capital. gives the match. preg_match(‘|. it’s worth using strtolower() first. $output). if frequent md5() generation is required. echo $output[1]. you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. but it does not lower-case anything else. and would like to make sure that no line exceeds 50 characters. and I am a neat freak. the more secure the crypto is. How can we destroy the session. It contains some long sentences.com?subject=Feedback”. A high volume site might be significantly slowed down.com?subject=Feedback” using regular expression of PHP? $text = “mailto:info@abc. >. the longer is the computation time to deliver the hash value. $output[1].What’s the difference between htmlentities() and htmlspecialchars()? htmlspecialchars only takes care of <. not the first one. use wordwrap() or chunk_split(). First off. single quote ‘. and get a properly formatted string.driving directions. but that doesn’t mean it’s free. htmlentities translates all occurrences of character sequences that have different meaning in HTML. Second. print $formatted. depending on the data that you’re encrypting. To avoid this. $text. $output[0].How can we extract string “abc. What will be printed is TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS. how can we unset the variable of a session? session_unregister() – Unregister a global variable from the current session session_unset() – Free all session variablesWhat are the different functions in sorting an array? Sorting functions in PHP: asort() . why would you ever use the less secure crc32() and sha1()? Crypto usage in PHP is simple. Note that the second index of $output.What’s the output of the ucwords function in this example? $formatted = ucwords(“TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS”). double quote ” and ampersand. How do I accomplish that with PHP? On large strings that need to be formatted according to some length specifications.So if md5() generates the most secure hash.com” from a string “mailto:info@abc.

What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command? DESCRIBE table_name. 2. a database name. crc32() and sha1() crypto on PHP? .How many ways we can pass the variable through the navigation between the pages? At least 3 ways: 1. count() will return 1.What’s the difference between md5(). and get it back from session in the next page. or a field name in MySQL? Database name: 64 characters Table name: 64 characters Column name: 64 charactersHow many values can the SET function of MySQL take? MySQL SET function can take zero or more values. but at the maximum it can take 64 values. Put the variable into a hidden form field.How can we find the number of rows in a table using MySQL? Use this for MySQL SELECT COUNT(*) FROM table_name. 3. Interestingly if you just pass a simple var instead of an array.arsort() ksort()krsort() uksort() sort() natsort() rsort()How can we know the count/number of elements of an array? 2 ways: a) sizeof($array) – This function is an alias of count() b) count($urarray) – This function returns the number of elements in an array. Put the variable into cookie in the first page. and get it back from the form in the next page.What is the maximum length of a table name. Put the variable into session in the first page. and get it back from the cookie in the next page.

Give the syntax of GRANT commands? The generic syntax for GRANT is as following GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password] Now rights can be: a) ALL privilages b) Combination of CREATE.* or some specific database by database. UPDATE and DELETE etc.Give the syntax of REVOKE commands? The generic syntax for revoke is as following REVOKE [rights] on [database] FROM [username@hostname] Now rights can be: a) ALL privileges b) Combination of CREATE. DROP.The major difference is the length of the hash generated. SELECT CURRENT_TIME(). SELECT CURTIME(). SELECT. DROP.table_name. echo “$num_rows rows found”.How many ways we can we find the current date using MySQL? SELECT CURDATE(). UPDATE and DELETE etc.How can we find the number of rows in a result set using PHP? Here is how can you find the number of rows in a result set in PHP: $result = mysql_query($any_valid_sql.We can grant rights on all database by using *.* or a specific table by database. and md5() returns a 160 bit value. CRC32 is. We can grant rights on all databse by usingh *. SELECT CURRENT_DATE().* or a specific table by database. INSERT. 32 bits. $database_link).What is the difference between CHAR and VARCHAR data types? . $num_rows = mysql_num_rows($result). INSERT. This is important when avoiding collisions.table_name. evidently. while sha1() returns a 128 bit value.* or some specific database by database. SELECT.

CHAR is a fixed length data type. For example. Great tool but you need to make sure that: a) Data must be delimited b) Data fields must match table columns correctlyHow can we know the number of days between two given dates using MySQL? Use DATEDIFF() SELECT DATEDIFF(NOW(). VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. use an ORDER BY clause.’2006-07-01′).How can I load data from a text file into a table? The MySQL provides a LOAD DATA INFILE command. The hash is a 32-character hexadecimal number.What is the functionality of MD5 function in PHP? string md5(string) It calculates the MD5 hash of a string. You can load data from a file. so numbers 10 and 11 will be compared. . CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example.How can we encrypt and decrypt a data present in a mysql table using mysql? AES_ENCRYPT() and AES_DECRYPT()Will comparison of string “10″ and integer 11 work in PHP? Yes. “Hello!” will be stored as “Hello!” in VARCHAR(10) column. “Hello!” will be stored as “Hello! ” in CHAR(10) column. internally PHP will cast everything to the integer type. The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive.How can we change the name of a column of a table? This will change the name of column: ALTER TABLE table_name CHANGE old_colm_name new_colm_nameHow can we change the data type of a column of a table? This will change the data type of a column: ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]What is the difference between GROUP BY and ORDER BY in SQL? To sort a result. and then use this temporary table to discover groups and apply aggregate functions (if any). VARCHAR is a variable length data type.

WWW’s ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. mysql_fetch_object(). This information is incorporated into Web server and browser software.[col2].…[coln]. . if you want to count all items in group. Tells DBMS to group (aggregate) results with same value of column col1. GROUP BY [col1]. then we write session_register(). AVG(col1) with it. When browser sees such header it shows the data as it would be a file (for example image) Some examples of MIME types: audio/x-ms-wmp image/png application/x-shockwave-flash Answer 2: Multipurpose Internet Mail Extensions. SUM(col1). …How can we know that a session is started or not? A session starts by session_start() function.…[coln]. MIME has a header which is added to a beginning of the data.What is meant by MIME? Answer 1: MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail.[col2]. it always declares first.ORDER BY [col1]. The standard provides for a system of registration of file types with information about the applications needed to process them. If two rows will have the same value in col1 it will try to sort them according to col2 and so on. and enables the automatic recognition and display of registered file types. mysql_fetch_row()? Answer 1: mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array. sum all values or view average. However browsers also uses MIME standard to transmit files.What are the differences between mysql_fetch_array().mysql_fetch_object() -> Fetch a result row as an object. Tells DBMS according to what columns it should sort the result. This session_start() is always declared in header portion. You can use COUNT(col1).

myd Table structure is stored in name.phpWhat are the differences between mysql_fetch_array(). means there should not be functions or classes or variables with the same name in abc. then session will continue in the browser. If connection is lost and you recreate connection. Returns an object with properties that correspond to the fetched row. mysql_fetch_object – Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.).PHP and makeit. but here are some things to make sure of: (including abc.Can we use include(abc. The session data will be deleted after session time out.PHP”? Yes we can include that many times we want.myiWhat is the difference between PHP4 and PHP5? PHP4 cannot support oops concepts and Zend engine 1 is used.If we login more than one browser windows at the same time with same user and after that we close one window.PHP) two times in a PHP page makeit. mysql_fetch_object(). etc. mysql_fetch_row()? mysql_fetch_array – Fetch a result row as an associative array and a numeric array. $row->email. the file names are case-sensitive) there shouldn’t be any duplicate function names. mysql_fetch_object() returns an object ($row->name. etc.). or FALSE if there are no more rows . etc.What are the MySQL database files stored in system ? Data is stored in name. If browser is closed then session is lost. while the latter returns a the results an array containing both numeric and associative keys ($row['name']. $row['email']. then is the session is exist to other windows or not? And if yes then why? If no then why? Session depends on browser. $row[1].mysql_fetch_row() -> Fetch a result set as a regular array(). Error supporting is increased in PHP5.frm Index is stored in name. Answer 2: The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0]. PHP5 supports oops concepts and Zend engine 2 is used.).PHP. XML and SQLLite will is increased in PHP5.

you can first read the data from one server into session variables. The row is returned as an array. Each result column is stored in an array offset. a numeric array. key_str)How can I retrieve values from one database server and store them in other database server using PHP? For this purpose. Beta MySQL 5.mysql_fetch_row() – Fetches one row of data from the result associated with the specified result identifier. PHP 5.0In how many ways we can retrieve data in the result set of MYSQL using PHP? mysql_fetch_array – Fetch a result row as an associative array. key_str) AES_DECRYPT(crypt_str.What is meant by nl2br()? Anwser1: nl2br() inserts a HTML tag <br> before all new line characters \n in a string. echo nl2br(“god bless \n you”).1. or both mysql_fetch_assoc – Fetch a result row as an associative arraymysql_fetch_object – Fetch a result row as an object mysql_fetch_row —.Get a result row as an enumerated arrayWhat are the functions for IMAP? imap_body – Read the message body imap_check – Check current mailbox imap_delete – Mark a message for deletion from current mailbox imap_mail – Send an email messageWhat are encryption functions in PHP? CRYPT() .Who is the father of PHP and what is the current version of PHP and MYSQL? Rasmus Lerdorf. Then connect to other server and simply insert the data into the database. output: god bless<br> youHow can we encrypt and decrypt a data presented in a table using MySQL? You can use functions: AES_ENCRYPT() and AES_DECRYPT() like: AES_ENCRYPT(str. starting at offset 0.

MD5()What is the difference between htmlentities() and htmlspecialchars()? htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used) htmlentities() – Convert ALL special characters to HTML entitiesWhat is the functionality of the function htmlentities? htmlentities() – Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways. height) of an image using php image functions? To know the image size use getimagesize() function To know the image width use imagesx() function To know the image height use imagesy() functionHow can we increase the execution time of a php script? By the use of void set_time_limit(int seconds) Set the number of seconds a script is allowed to run. all characters which have HTML character entity equivalents are translated into these entities. the max_execution_time value defined in the php. so restoring it is very easy: shell> mysql “. In other words. width. the script will run for a total of 45 seconds before timing out. type.How can we get the properties (size. When called. If this is reached. If seconds is set to zero. if it exists. The default limit is 30 seconds or. Answer 2: To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory .ini.”Executed”. the script returns a fatal error. set_time_limit() restarts the timeout counter from zero. except with htmlentities().HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT? Answer 1: Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir The full backup file is just a set of SQL statements. no time limit is imposed. if the timeout is the default 30 seconds. and 25 seconds into script execution a call such as set_time_limit(20) is made.

// already expired time Reset a cookie by specifying its name only Example: setcookie(‘Test’).’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory mysqldump: Dumping Table Structure and Data Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). -d. -t.'time’) . Test – cookie variable name $i – value of the variable ‘Test’ time()+3600 – denotes that the cookie will expire after an one hourHow to reset/destroy a cookie ? Reset a cookie by specifying expire time in the past: Example: setcookie(‘Test’.time()+3600).time()-3600). variable – name of the cookie variable value – value of the cookie variable time – expiry time Example: setcookie(‘Test’.What types of images that PHP supports ? Using imagetypes() function to find out what types of images are supported in your PHP engine.'value’.$i.imagetypes() – Returns the image types supported. no-data Don’t write any row information for the table. The dump will contain SQL statements to create the table and/or populate the table.$i. no-create-info Don’t write table creation information (the CREATE TABLE statement). . This is very useful if you just want to get a dump of the structure for a table!How to set cookies? setcookie(‘variable’.

myform.This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP.submit().8. FALSE otherwise. and MySQL? PHP: PHP 5. IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. else alert(‘Not an integer’). Syntax isNaN(number) Parameter Description number Required. Case Studio Smart DrawHow can I know that a variable is a number or not using a JavaScript? Answer 1: bool is_numeric( mixed var) Returns TRUE if var is a number or a numeric string. PHP. onfocus.Tools used for drawing ER diagrams.How many ways can we get the value of current session id? session_id() returns the session id for the current session. etc ) document.2. The following bits are returned. This will submit the form.Check if a variable is an integer in JAVASCRIPT ? var myValue =9.How can we destroy the cookie? Set the cookie with a past expiration time. if(parseInt(myValue)== myValue) alert(‘Integer’).What are the current versions of Apache. Answer 2: Definition and Usage The isNaN() function is used to check if a value is not a number. The value to be testedHow can we submit from without a submit button? Trigger the JavaScript code on any event ( like onSelect of drop down list box.5 .

but instead of requiring an implementation with the name of that class attached by the double colon syntax. For some systems. Php is more faster that asp or any other scripting language. MySQL. shopping carts. How can we get second of the current time using date function? $second = date(“s”). OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. an OO approach can speed development time since many objects are standard across systems and can be reused.1 Apache: Apache 2. a global function or member function of another class provides the match. protected: .MySQL: MySQL 5. Such functions can be declared either as member functions of one class or as global functions. shipping. Mysql is world most popular open source database. as if they were themselves members of that class. objects can easily be modified and added to a system there by reducing maintenance costs. Apache is a better server that IIS both in functionality and security. In either case they can be set to be friends of other classes. OO programming is also considered to be better at modeling the real world than is procedural programming. by using a friend specifier in the class that is admitting them. etc. Such functions can use all attributes of the class which names them as a friend.What are the features and advantages of OBJECT ORIENTED PROGRAMMING? One of the main advantages of OO programming is its ease of modification.class mylinkage { private: mylinkage * prev.What is the use of friend function? Friend functions Sometimes a function is best shared among a number of different classes. servers and operating systems? All of those are open source resource. A friend declaration is essentially a prototype for a member function. Php) instead of combination of other software programs. Security of Linux is very more than windows. Components that manage dates.1What are the reasons for selecting LAMP (Linux. Apache. can be purchased and easily modified for a specific system. mylinkage * next. It allows for more complicated and flexible interactions.

friend void set_prev(mylinkage* L. mylinkage* N). It is also possible to specify all the functions in another class as friends. } Friends in other classes It is possible to specify a member function of another class as a friend as follows: class C { friend int B::f1(). class A . by specifying the entire class as a friend. mylinkage * N ) { N->prev = L. }. mylinkage * pred(). void set_next(mylinkage* L). }. } void set_prev(mylinkage * L. public: mylinkage * succ(). void mylinkage::set_next(mylinkage* L) { next = L. mylinkage(). }. class B { int f1().

We will return to it when we look at overloading. MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. Indexes are used to find rows with specific column values quickly. Triggers will also be implemented. as more of the work is done on the server side and less on the client (application) side. indexes? A stored procedure is a set of SQL commands that can be compiled and stored in the server.What is the maximum size of a file that can be uploaded using PHP and how can we change this? You can change maximum size of a file set upload_max_filesize variable in php. the more this costs. This provides better overall performance because the query has to be parsed only once. The definition of those methods must be in its extending class. MySQL must begin with the first row and then read through the entire table to find the relevant rows. Abstract methods are the methods. A trigger is effectively a type of stored procedure.{ friend class B.How can we get second of the current time using date function? $second = date(“s”). All the methods must be define by its implemented class. The larger the table. triggers. }. You can also raise the conceptual level by having libraries of functions in the server. clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. one that is invoked when a particular event occurs. stored procedures of course do increase the load on the database server system. Once this has been done. Friend functions allow binary operators to be defined which combine private data in a pair of objects. If the table has an index for the columns in question. This is particularly powerful when using the operator overloading features of C++. For example. which are declare in its class but not define.What are the advantages of stored procedures. this is at least 100 . and less information needs to be sent between the server and the client.ini fileHow can I make a script that can be bilingual (supports English. That means all the methods only declared but not defined. German)? You can change char set variable in above line in the script to support bi language. If a table has 1. you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.What are the difference between abstract class and interface? Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract.000 rows. However. Interface: Interfaces are one type of class where all the methods are abstract. Without an index.

The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. This allows a table to exceed the maximum individual file size. database performance can be adversely affected.2-Intel 32-bit 2GB (LFS: 4GB) Linux 2. the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. because this minimizes disk seeks. This is only a rough guide and is not intended to be definitive. The tablespace can include raw disk partitions. With the MyISAM storage engine in MySQL 3. the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes.22 had a 4GB (4 gigabyte) limit on table size. and a higher level of normalization cannot be achieved until the previous levels have been achieved . MySQL is bound by that constraint. which allows extremely large tables. If the time required to open a file in the directory increases significantly as the number of files increases.4+ (using ext3 filesystem) 4TB Solaris 9/10 16TB NetWare w/NSS filesystem 8TB Win32 w/ FAT/FAT32 2GB/4GB Win32 w/ NTFS 2TB (possibly larger) MacOS X w/ HFS+ 2TBExplain normalization concept? The normalization process involves getting our data to conform to three progressive normal forms. be sure to check the documentation specific to your operating system. MySQL 3.What is maximum size of a database in mysql? If the operating system or filesystem places a limit on the number of files in a directory. Operating System File-size Limit Linux 2.23. If you need to access most of the rows. not by MySQL internal limits. The following table lists some examples of operating system file-size limits. The maximum tablespace size is 64TB.times faster than reading sequentially. it is faster to read sequentially. With this larger allowed table size. The amount of available disk space limits the number of tables. For the most up-to-date information.

the normal forms are progressive. Second Normal Form Where the First Normal Form deals with redundancy of data across a horizontal row. those. but dependant on another value in the tableWhat’s the difference between accessing a class method via -> and via ::? :: is allowed to access methods that can perform static operations.e.What are the advantages and disadvantages of CASCADE STYLE SHEETS? External Style Sheets Advantages Can control styles for multiple documents at once Classes can be created for use on multiple HTML element types in many documents Selector and grouping methods can be used to apply styles under complex contexts Disadvantages An extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitions Embedded Style Sheets .(there are actually five normal forms. and that every column stores the least amount of information possible (making the field atomic). so to achieve Second Normal Form. which do not require object initialization. Third Normal Form I have a confession to make. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key. As stated earlier. I do not often use Third Normal Form. We want to ensure that there is no duplication of data in a given row. i. but the last two are mainly academic and will not be discussed). Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. First Normal Form The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. your tables must already be in First Normal Form.

When you want to show some part of a text displayed on an HTML page in red font color? What different possibilities are there to do this? What are the advantages/disadvantages of these methods? There are 2 ways to show some part of a text in red: 1. Using HTML tag <span style=”color: red”>When viewing an HTML page in a Browser. of records. Classes are extended using the keyword ‘extends’. also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in two or more tables. Using HTML tag <font color=”red”> 2. the Browser often keeps this page in its cache.Advantages Classes can be created for use on multiple tag types in the document Selector and grouping methods can be used to apply styles under complex contexts No additional downloads necessary to receive style information Disadvantage This method can not control styles for multiple documents at once Inline Styles Advantages Useful for small quantities of style definitions Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods Disadvantages Does not distance style information from content (a main goal of SGML/HTML) Can not control styles for multiple documents at once Author can not create or control classes of elements to control multiple element types within the document Selector grouping methods can not be used to create complex element addressing scenariosWhat type of inheritance that php supports? In PHP an extended class is always dependent on a single base class. multiple inheritance is not supported. What can be possible . that is.How can we change the name of a column of a table? MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_nameALTER TABLE tableName CHANGE OldName newName.How can increase the performance of MySQL select query? We can use LIMIT to stop MySql for further search in table after we have received our required no.

Possible values are CP_ACP. the Web page may still be cached in the Temporary Internet Files folder.advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)? When you use the metatag in the header section at the beginning of an HTML Web page. allow_dcom has to be set to TRUE in php. Try this: /href=”([^"]*)”/iHow can I use the COM components in php? The COM class provides a framework to integrate (D)COM components into your PHP scripts. When the HTML code is parsed. If it is there. server_name: name of the DCOM server from which the component should be fetched. A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled.What are the different ways to login to a remote server? Explain the means. which can be used to identify the URL from within a HTML link tag.ini. To properly prevent the Web page from appearing in the cache. localhost is assumed. When the metatag is read. string COM::COM( string module_name [. metatags are inserted in the header section of an HTML document. codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. //open an empty document . which appears at the beginning of the document. CP_SYMBOL. it is removed. CP_UTF7 and CP_UTF8. place another header section at the end of the HTML document. CP_MACCP. If NULL. Internet Explorer looks for the existence of the page in cache at that exact moment. Usage: $word->Visible = 1. Parameters: module_name: name or class-id of the requested component.Please give a regular expression (preferably Perl/PREG style). To allow DCOM com. string server_name [. it is read from top to bottom. CP_THREAD_ACP. advantages and disadvantages? There is at least 3 ways to logon to a remote server: Use ssh or telnet if you concern with security You can also use rlogin to logon to a remote server. Usually. CP_OEMCP. int codepage]]) – COM class constructor.

and windows? Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals. JSP. . upload_tmp_dir = C:\apache2triad\temp . //closing word $word->Quit().ini file for file uploading? Make the following line uncomment like: . $word->Documents[1]->SaveAs(“Useless test. upload_max_filesize = 2MHow can I set a cron and how can I execute it in Unix. Maximum allowed size for uploaded files.doc”). //free the object $word->Release().$word->Documents->Add(). specified).How many ways we can give the output to a browser? HTML output PHP. file_uploads = On . which means order of time. Linux. $word = null. Temporary directory for HTTP uploaded files (will use system default if not . In Windows. ASP. Whether to allow HTTP file uploads. The name Cron is in fact derived from the same word from which we get the word chronology. //do some weird stuff $word->Selection->TypeText(“This is a test…”). it’s called Scheduled Tasks. Servlet Function Script Language output Function Different Type of embedded Package to output to a browserWhat is the default session time in php and how can I change it? The default session time in php is until closing of browser What changes I have to do in php.

it needs to be passed through Apache. In other words. The reason is that. you will be able to enter the commands that you wish to run. Upon employing this command. the ranges permitted for each field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can also include multiple values for each entry. which is a wildcard that allows any value. My version of Linux uses the text editor vi. with the exception of the command itself. simply by separating each value with a comma. command can be any shell command and. as opposed to an Apache module).# crontabThis command ‘edits’ the crontab. So. The syntax of this file is very important – if you get it wrong. In addition to an asterisk (*). the page needs to be called via a browser or other means of retrieving . as we will see momentarily. nothing will happen (barring very special configurations that have PHP compiled as an executable. our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all seems simple enough. can also be used to execute a Web document such as a PHP file. right? Not so fast! If you try to run a PHP script in this manner. You can find information on using vi here. your crontab will not function properly. if we want to run a script every Tuesday morning at 8:15 AM. The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command All the variables. are numerical constants.The easiest way to use crontab is via the crontab command. in order for PHP to be parsed.

} } redirect(‘http://maosjb.example.’”. I’ll assume that your server configuration includes wget. as is the case with most default configurations. echo ”. type the following: # wget help If you are greeted with a wget package identification. Using php function: header(“Location:http://maosjb. This is what my crontab will look like: 0 4 * * 1.php file we created in the first part of this article.5 we get http://www. ?> 2.com/mailstock. echo ”. We saved it in our document root. int http_response_code]])What type of headers have to be added in the mail function to attach a file? $boundary = ‘–’ . Redhat or Mandrake). and send you your precious closing bell report? Since I’m located in the Eastern timezone.com “).com/file.3.example.4.2.location.$filename.href=”‘. If you’re using an RPM-based system (e. To test your configuration. The online payment gateway allows you to immediately verify credit card transactions and authorize funds on a customer’s credit card directly from your Web site.g. md5( uniqid ( rand() ) ). Remember that we wanted it to run at 4PM Eastern time. bool replace [.List out different arguments in PHP header function? void header ( string string [. For our purposes. echo ”. Using Java script: ‘. echo ‘window. . we can go ahead and set up our crontab to use 4:00. 1. like so: # wget http://www. log in to shell.php Now. You could execute the PHP by invoking wget on the URL to the page.Web content. but if you live elsewhere.phpSteps for the payment gateway processing? An online payment gateway is the interface between your merchant account and your Web site.com’).’. echo ”. so it should be accessible via the Internet. you might have to compensate for the time difference when setting this value. let’s go back to the mailstock. It then passes the transaction off to your merchant bank for processing. it is installed in your system. commonly referred to as transaction batchingHow many ways I can redirect a PHP page? Here are the possible ways of php page redirection.

$headers = “From: \”Me\”\n”; $headers .= “MIME-Version: 1.0\n”; $headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\”";What is the difference between Reply-to and Return-path in the headers of a mail function? Reply-to: Reply-to is where to delivery the reply of the mail. Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.How to store the uploaded file to the final location? move_uploaded_file ( string filename, string destination) This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination. If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.Explain about Type Juggling in php? PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer. An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated. $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + “10 Little Piggies”; // $foo is integer (15) $foo = 5 + “10 Small Pigs”; // $foo is integer (15) If the last two examples above seem odd, see String conversion to numbers.

If you wish to change the type of a variable, see settype(). If you would like to test any of the examples in this section, you can use the var_dump() function. Note: The behavior of an automatic conversion to array is currently undefined. Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being “f”, or should “f” become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes “f”, the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:How can I embed a java programme in php file and what changes have to be done in php.ini file? There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension. The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process. Example Code: getProperty(‘java.version’) . ”; echo ‘Java vendor=’ . $system->getProperty(‘java.vendor’) . ”; echo ‘OS=’ . $system->getProperty(‘os.name’) . ‘ ‘ . $system->getProperty(‘os.version’) . ‘ on ‘ . $system->getProperty(‘os.arch’) . ‘ ‘; // java.util.Date example $formatter = new Java(‘java.text.SimpleDateFormat’, “EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”); echo $formatter>format(new Java(‘java.util.Date’)); ?> The behaviour of these functions is affected by settings in php.ini. Table 1. Java configuration options Name Default Changeable

java.class.path NULL PHP_INI_ALL Name Default Changeable java.home NULL PHP_INI_ALL java.library.path NULL PHP_INI_ALL java.library JAVALIB PHP_INI_ALLExplain the ternary conditional operator in PHP? Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.What’s the difference between include and require? It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.How many ways can we get the value of current session id? session_id() returns the session id for the current session.

What is meant by MVC (Model View Controller)? MODEL VIEW CONTROLLER, is a software architecture, currently considered an architectural pattern used in software engineering. This isolates business logic from presentation logic. 1. The Model represents the application data 2. The View renders a presentation of model data 3. The Controller handles and routes requests made by the client

Sign up to vote on this title
UsefulNot useful