Web Trainings Institute

PHP & MySQL

1

Web Trainings Institute

Table of Contents Installation Introduction PHP and MySQL PHP Installation MySQL Installation Apache Installation Configuring and Testing software’s. XAMPP and WAMPP Installation

PHP Basics

Embedding PHP in HTML Embedding HTML in PHP Introduction of Variable Using variables Understanding Data Types Using Operators Writing Statements and Comments Using Conditional Statements If(), else if() and else if condition Statement Switch() Statements Using the while() Loop Using the do() Loop Using the for() Loop

Arrays and Custom Functions Creating an Array 2

Web Trainings Institute

Modifying Array Elements Processing Arrays with Loops Grouping Form Selections with Arrays Using Array Functions Creating User-Defined Functions Defining and Invoking Functions

Creating basic programs with PHP Reading and Writing Files Reading Data from a File Writing Data to a File Testing File Attributes. Managing Sessions and Using Session Variables Creating a Session and Registering Session Variables Destroying a Session Storing Data in Cookies Setting Cookies Retrieving Cookie Data Dealing with Dates and Times Executing External Programs

Simple Project without using Database

Learning MySQL Understanding an RDBMS Understanding a Relational Database Understanding Tables, Records, and Fields Understanding Primary and Foreign Keys 3

Web Trainings Institute

Understanding SQL and SQL Queries Understanding Database Normalization Using the MySQL Command-Line Client

Working with Databases and Tables Creating Databases Creating Tables Specifying Field Data Types Selecting the Most Appropriate Data Type Adding Field Modifiers and Keys Selecting a Table Type Altering Tables Altering Table and Field Names Altering Field Properties Adding and Removing Fields and Keys Altering Table Types Backing Up and Restoring Databases and Tables Backing Up Databases and Tables Restoring Databases and Tables from Backup Dropping Databases and Tables Viewing Database, Table, and Field Information

Editing Records and Performing Queries Inserting Records Editing and Deleting Records Performing Queries Retrieving Specific Columns Filtering Records with a WHERE Clause 4

Web Trainings Institute

Using Operators Sorting Records and Eliminating Duplicates Limiting Results Using Built-In Functions Grouping Records Joining Tables Using Subqueries Using Table and Column Aliases

Using the MySQL Security System Understanding the Need for Access Control Understanding How MySQL Access Control Works Assigning, Revoking, and Viewing User Privileges Working with User Accounts and Password Creating and Removing User Accounts Altering User Passwords

Using PHP with MySQL Managing Database Connections Performing Queries Processing Result Sets Queries Which Return Data Queries That Alter Data Handling Errors Using Ancillary Functions

Creating Forms and Validations with JavaScript HTML Basics 5

Web Trainings Institute

Creating Forms with HTML

Java Script Introduction to Java Scripting Types of Java Scripts Variables, operators, loops Using Objects, Events Common java script functions Using JavaScript in Dreamweaver Java Script Validations

Project Requirements analysis of Project Documentation of Project Project code Execution Project Testing

Introduction PHP PHP stands for "PHP: HyperText Preprocessor". PHP is a server side scripting language for making logic driven websites. Ever wonder how they made that "contact us" form on their site, which sends out emails? Well, they used PHP. Or, how they made that image upload tool? Well, they used PHP. PHP written scripts can use databases to keep track of your customer's and visitors activities on your site, send out periodical newsletters to your subscribers, upload files or images and drive the content on your site dynamically. The possibilities are endless. Most of the social networking websites you visit are writing in PHP. Yep! PHP is that powerful.

PHP is an excellent choice for Web programming. It has many advantages over other languages, including other Web-oriented languages. To get a very general understanding of how the common Web 6

Web Trainings Institute

programming languages compare, let’s compare them. ASP is Microsoft’s Web programming environment. (It’s not a language itself because it allows the programmer to choose from a few actual languages, such as VBScript or JScript.) ASP is simple, but too simple for programs that use complex logic or algorithms.

PHP’s primary use certainly isn’t to track résumés anymore; it has grown to be able to do that and just about anything else. To giveyou a better idea of what PHP can do, here are some of its common uses:



User forms, Forums, Blogs



CMS, Shopping carts, Portals, Classified Sites, Social Networking



Custom application development

How PHP works ? PHP sits between your browser and the web server. When you type in the URL of a PHP website in your browser, your browser sends out a request to the web server. The web server then calls the PHP script on that page. The PHP module executes the script, which then sends out the result in the form of HTML back to your browser, which you see on the screen. Here is a basic php diagram which illustrate the process.

PHP Process Diagram

7

Web Trainings Institute

Installation of PHP 5 1. Download & Unpack Download and install PHP from http://www.php.net/downloads.php, you should grab the newest 5.x.x Windows Binaries zip package that will work on apache.

My file was named: php-5.2.9-1-Win32.zip 2. Unzip php. In my case, I unzipped to: C:\php\ 3. Rename C:\php\php.ini-dist it to php.ini 4. Edit your php.ini Open php.ini in a text editor and scroll down about halfway through the file and look for doc_root then change it to point to whatever your Apache DocumentRoot is set to. In my case: doc_root = "C:\public_html"

Scroll down about 7 more lines and change the extension_dir from extension_dir = "./" to the location of the ext directory after you unzipped PHP. in my case: extension_dir = "C:\php\ext"

If you are going to be using your server for testing, i recommend (this is optional) you search and change the error reporting to give you info on any errors, notices, or bad coding. If you want to enable this type of stuff, search for error_reporting for and change: error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT to error_reporting = E_ALL | E_NOTICE | E_STRICT 5. Editing Apache Conf File 8

Web Trainings Institute

Using Notepad open httpd.conf (should be start-menu shortcut "Apache HTTP Server 2.2 > Configure Apache Server > Edit the Apache httpd.conf Configuration File"). Either at the very beginning or end of the file add the following lines: (NOTE: be sure to change BOTH C:/php parts to the directory you installed your php to) LoadModule php5_module "C:/php/php5apache2_2.dll" AddType application/x-httpd-php .php PHPIniDir "C:/php"

Note: If you installed the older Apache 2.0, instead of the above lines, you will need to use the lines listed on the bottom step of the Apache 2.0 tutorial. 6. [OPTIONAL] Editing Apache Conf File (part 2) To get apache to automatically look for an index.php, search httpd.conf for DirectoryIndex (about line 212) and add the files you want apache to look for when a directory is loaded (if it doesn't find any of these files, it displays folder contents). Mine looks like: DirectoryIndex index.php index.html default.html 7. Testing Restart Apache if it is already running (if it doesn't start or you get errors, use your Apache "Test Configuration" shortcut in the Start Menu to see why).

To test your PHP simply create a test.php file in your Apache "DocumentRoot" folder (E:\public_html\ in my case). In your test.php file, type these 3 lines and then load the file in 9

Web Trainings Institute

your browser like http://localhost/test.php (you should get a whole long list of php variables, settings, etc): 8. Documentation Suggestion One weird thing I have noticed about PHP is that it does not come with documentation of any kind. If you are a php developer/programmer, I suggest you download the documentation. Downloads can be found on http://www.php.net/download-docs.php and I personally recommend the "English - Windows HTML Help" (chm) version as the search is so handy, although they all contain the same information. Further Installation Guide : http://php.net/manual/en/install.windows.php

Introduction to MySQL MySQL is currently the most popular open source database server in existence. On top of that, it is very commonly used in conjunction with PHP scripts to create powerful and dynamic server-side applications MySQL has the following features 

Ease of Use



Scalability and Portability



Security



Reliability



Wide Application Support

10

Web Trainings Institute

Installation of MySQL 5.1 1. Download MySQL v5.1 Download MySQL from http://dev.mysql.com/downloads/mysql/5.1.html Just make sure you get a Windows Essentials (x86) binary version. (after you click the "pick a mirror," if it asks you to login, scroll down a little and click the "No thanks, just take me to the downloads!" link under the login form)

My file was named: mysql-essential-5.1.33-win32.msi 2. Install MySQL v5.1 Run the MSI file and use the following settings o

Typical Setup

o

Skip Sign-Up

o

make sure "Configure the MySQL Server now" is checked

o

"Detailed Configuration"

o

"Developer Machine"

o

"Multifunctional Database"

o

"InnoDB Tablespace Settings" - leave everything default

o

"Decision Support (DSS)/OLAP"

o

make sure "Enable TCP/IP Networking" is checked and leave the port number at 3306 (at this point, if you have a firewall, it will usually try to access itself on the localhost) Leave "Enable Strict Mode" checked

o

"Standard Character Set"

o

check "Install As Windows Service" and I would recommend leaving "Launch the MySQL Server automatically" checked. 11

Web Trainings Institute

o

enter your root password and I would recommend leaving "Enable root access from remote machines" unchecked

o

then hit "execute" and it'll install and set it up.

3. Getting PHP5 to work with MySQL - Official Info Unfortunately PHP5 removed built-in support for MySQL. To get it to work, the easiest way is to copy the mysql library file by hand. Open the folder you unzipped your PHP to. Copy the libmysql.dll file (should be located like C:\php\libmysql.dll ) into your Window's System folder (usually C:\Windows\System32\ although might be C:\WinNT\System\ or something).

Then open up your php.ini in a text editor and search for ;extension=php_mysql.dll and remove the ; infont of that line.

Restart Apache and see if you get any errors. If it complains about "php_mysql.dll" either your extension directory isn't correct or windows can't find libmysql.dll 4. Testing MySQL Testing MySQL is not exactly easy. However, here are the common connection strings for PHP. I recommend downloading phpMyAdmin and using it to create and manage your databases, etc.

PHP Connection test
// username and password to log onto db server $dbUser='root'; 12

Web Trainings Institute

$dbPass='';

// name of database $dbName='test';

$link = mysql_connect("$dbServer", "$dbUser", "$dbPass") or die("Could not connect"); print "Connected successfully
"; mysql_select_db("$dbName") or die("Could not select database"); print "Database selected successfully
";

// close connection mysql_close($link); ?>

Introduction to Apache The Apache HTTP Server, commonly referred to as Apache is web server software notable for playing a key role in the initial growth of the World Wide Web. This server is used in LAMP Development Enviroment. The Apache Web Server is where it all started, and, although now just one project among many, it has continued to develop new and exciting features over its entire 15 year history. Installation of Apache 2.2.X 1. Download & Unpack Go to http://www.apache.org/dist/httpd/binaries/win32/ and choose a mirror. You want the latest win32-x86-no_ssl.msi "MSI Installer Package" release.

My file was named: apache_2.2.11-win32-x86-no_ssl.msi 13

Web Trainings Institute

NOTE: Apache sometimes moves the "quick download" link to the win32 binary. The long way to officially find it is Download > Other files > binaries folder (not the "Binary Releases" info link at the top) > win32 folder > then the latest win32-x86-no_ssl.msi release 2. Install When you install Apache, you'll get a prompt for "Server Information." Here is the settings I used: Network Domain: localhost Server Name: localhost Admin Email: (your any email)

[checked]: for All Users, on Port 80, as a Service 3. Starting/Stopping Apache After installing, Apache2 automatically starts. The The

icon in the System Tray means it started.

icon means the "Monitor Apache Servers" is running, but Apache2 isn't started.

You can easily start/stop/restart Apache and Apache2 via that icon in your System Tray. If you get "The requested operation has failed!" error while starting apache use the "Test Configuration" shortcut in the Start Menu to find the error (if the text window pops up then closes before you can read it, your config file is fine). 4. Testing Now the ultimate test. To see if it's serving. Open your browser and head to: http://127.0.0.1/ or http://localhost/ 14

Web Trainings Institute

If it shows the It works! you have your server software installed and running. 5. Making Apache point to your files Using Notepad open C:/Program Files/Apache Software Foundation/Apache2.2/htdocs (in the start-menu there should also be a "Apache HTTP Server 2.2 > Configure Apache Server > Edit the Apache httpd.conf Configuration File" shortcut) and search for DocumentRoot. Change it from something like DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs" to the location where your HTML files and site are located. In my case: DocumentRoot "C:/public_html" NOTE: The first time i installed Apache2, i accidentally changed ServerRoot. Make sure you change the correct line which is DocumentRoot and which is down about line 150. 6. Then scroll down about one page and change: to point to the same location you set DocumentRoot to in the last step. Restart apache to make the changes take effect

15

Web Trainings Institute

LAMP ENVIRONMENT

16

Web Trainings Institute

PHP Basics Embedding PHP in HTML One of the nicer things about PHP is that, unlike CGI scripts, which require you to write server-side code to output HTML, PHP lets you embed commands in regular HTML pages. These embedded PHP commands are enclosed within special start and end tags, which are read by the PHP interpreter when it parses the page.

Here is an example of what these tags looks like:

Example

Q: This creature can change color to blend in with its surroundings. What is its name?

A: Chameleon'; ?> 17

Web Trainings Institute

Comments in PHP



Variables Variables are the building blocks of any programming language. A variable can be thought of as a programming construct used to store both numeric and nonnumeric data. The contents of a variable can be altered during program execution, and variables can be compared and manipulated using operators

PHP supports a number of different variable types—Booleans, integers, floating point numbers, strings, arrays, objects, resources, and NULLs—and the language can automatically determine variable type by the context in which it is being used. Every variable has a name, which is preceded by a dollar ($) symbol, and it must begin with a letter or underscore character, optionally followed by more letters, numbers, and underscores. For example, $popeye, $one_day, and $INCOME are all valid PHP variable names, while $123 and $48hrs are invalid variable names.

Q: Where can we learn php in hyderabad. What is the name of institute?

18

Web Trainings Institute

$answer"; ?>

Assigning and Using Variable Values To assign a value to a variable, use the assignment operator, the equality (=) symbol. This operator assigns a value (the right side of the equation) to a variable (the left side). The value being assigned need not always be fixed; it could also be another variable, an expression, or even an expression involving other variables, as here: To use a variable value in your script, simply call the variable by name, and PHP will substitute its value at run time. For example:

Saving Form Input in Variables Forms have always been one of the quickest and easiest ways to add interactivity to your web site. A form enables you to ask customers if they like your products and casual visitors for comments. PHP can simplify the task of processing webbased forms substantially, by providing a simple mechanism to read user data submitted through a form into PHP variables. Consider the following sample form: 19

Web Trainings Institute

Enter your message:
The most critical line in this entire page is the
tag: ...
As you probably already know, the method attribute of the
tag specifies the manner in which form data will be submitted (POST), while the action attribute specifies the name of the server-side script (message.php) that will process the information entered into the form. Here is what message.php looks like: $input"; ?> To see how this works, enter some data into the form (“boo”) and submit it. The form processor should read it and display it back to you (“you said: boo”). Thus, whenever a form is POST-ed to a PHP script, all variable-value pairs within that form automatically become available for use within the script through a special PHP container variable, $_POST. To then access the value of the form variable, use its name inside the $_POST container, as in the previous script. If the form uses GET instead of POST, simply retrieve values from $_GET instead of $_POST.

In PHP, a variable does not need to be declared before adding a value to it.You do not have to tell PHP which data type the variable is.PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP, the variable is declared automatically when you use it.

20

Web Trainings Institute

Datatypes Boolean : The simplest variable type in PHP, a Boolean variable simply specifies a true or false value. Example : $auth = true; Integer : An integer is a plain-vanilla number like 75, -95, 2000, or 1. Example : $age = 99; Floating-point : A floating-point number is typically a fractional number such as 12.5 or 3.149391239129. Floating point numbers may be specified using either decimal or scientific notation. $temperature = 56.89; String : A string is a sequence of characters, like 'hello' or 'abracadabra'. String values may be enclosed in either double quotes ("") or single quotes ('')

Detecting the Data Type of a Variable To find out what type a particular variable is, PHP offers the gettype() function, which accepts a variable or value as argument. The following example illustrates this: 21

Web Trainings Institute

String values enclosed in double quotes are automatically parsed for variable names; if variable names are found, they are automatically replaced with the appropriate variable value. See the following code snippet for an example: Note that if your string contains quotes, carriage returns, or backslashes, it’s necessary to escape these special characters with a backslash. The following example illustrates this: NULL Values PHP 4.x introduced a new data type for empty variables, called NULL. The NULL data type is “special”: it means that a variable has no value. A NULL is typically seen when a variable is initialized but not yet assigned a value, or when a variable has been de-initialized with the unset() function. To see an example of NULL in action, consider the following script:
Web Trainings Institute

// returns NULL echo gettype($me); ?>

Operators Arithmetic Operators Operator

Description

Example

Result

+

Addition

x=2 x+2

4

-

Subtraction

x=2 5-x

3

*

Multiplication

x=4 x*5

20

/

Division

15/5 5/2

3 2.5

%

Modulus (division remainder)

5%2 10%8 10%2

1 2 0

++

Increment

x=5 x++

x=6

--

Decrement

x=5 x--

x=4

Assignment Operators Operator

Example

Is The Same As

=

x=y

x=y

23

Web Trainings Institute

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

.=

x.=y

x=x.y

%=

x%=y

x=x%y

Comparison Operators Operator

Description

Example

==

is equal to

5==8 returns false

!=

is not equal

5!=8 returns true

<>

is not equal

5<>8 returns true

>

is greater than

5>8 returns false

<

is less than

5<8 returns true

>=

is greater than or equal to

5>=8 returns false

<=

is less than or equal to

5<=8 returns true

Logical Operators Operator

Description

Example

&&

and

x=6 y=3 (x < 10 && y > 1) returns true 24

Web Trainings Institute

||

!

or

x=6 y=3 (x==5 || y==5) returns false x=6 y=3

not

!(x==y) returns true

Examples Using Arithmetic Operators Using String Operators To add strings together, use the string concatenation operator, represented by a period (.). The following example illustrates this: 25

Web Trainings Institute

You can concatenate and assign simultaneously, as in the following: Using Comparison Operators To test whether two variables are different, use any one of PHP’s many comparison operators. The following listing demonstrates most of the important ones: $median); // less-than-or-equal-to operator // returns true if left side is less than or equal to right // returns false here $result = ($median <= $mode); // greater-than-or-equal-to operator // returns true if left side is greater than or equal to right // returns true here $result = ($median >= $mode); // equality operator // returns true if left side is equal to right // returns true here $result = ($mean == $mode); 26

Web Trainings Institute

// not-equal-to operator // returns true if left side is not equal to right // returns false here $result = ($mean != $mode); // inequality operator // returns true if left side is not equal to right // returns false here $result = ($mean <> $mode); ?> The result of a comparison test is always a Boolean value (either true or false). This makes comparison operators a critical part of your toolkit, as you can use them in combination with a conditional statement to send a script down any of its multiple action paths. Using === Operator Using Logical Operators To link together related conditions in a simple and elegant manner, use one of PHP’s four logical operators—logical AND, logical OR, logical XOR, and logical NOT—as illustrated in the following listing:
Web Trainings Institute

// returns true if all conditions are true // returns true here $result = (($user == 'joe') && ($pass == 'trym3')); // logical OR // returns true if any condition is true // returns false here $result = (($status < 1) || ($saveCookie == 0)); // logical NOT // returns true if the condition is false and vice-versa // returns false $result = !($saveCookie == 1); // logical XOR // returns true if any of the two conditions are true // returns false if both conditions are true // returns false here $result = (($status == 1) xor ($saveCookie == 1)); ?> Using the Auto-Increment and Auto-Decrement Operators The auto-increment operator is a PHP operator designed to automatically increment the value of the variable it is attached to by 1. It is represented by a double addition symbol (++). To see it in action, run the following script: Thus, is functionally equivalent to . There’s also a corresponding auto-decrement operator (--), which does exactly the opposite:
Web Trainings Institute

// decrement it $total--; // $total is now 9 ?>

Using the if() Statement In PHP, the simplest form of conditional statement is the if() statement, which looks like this: Here’s an example: = 100) { echo 'Very hot!'; } ?>

Using If-Else Statement

Using Switch
Web Trainings Institute

case 'UK': $capital = 'London'; break; case 'US': $capital = 'Washington'; break; case 'FR': $capital = 'Paris'; break; default: $capital = 'Unknown'; break; } ?>

Nesting Conditional Statements To handle multiple conditions, you can “nest” conditional statements inside each other. For example, this is perfectly valid PHP code:

Using the while() Loop The first—and simplest—loop to learn in PHP is the so-called while() loop. With this loop type, so long as the conditional expression specified evaluates to true, the loop will continue to execute. When the condition becomes false, the loop will be broken and the statements following it will be executed. Here is the syntax of the while() loop:
Web Trainings Institute

while (condition is true) { do this; } ?> Example:

Using the do() Loop A while() loop executes a set of statements while a specified condition is true.If the condition evaluates as false on the first iteration of the loop, the loop will never be executed. In the previous example, if the lower limit is set to a value greater than the upper limit, the loop will not execute even once.However, sometimes you might need to execute a set of statements at least once, regardless of how the conditional expression evaluates. For such situations, PHP offers the do-while() loop. The construction of the do-while() loop issuch that the statements within the loop are executed first, and the condition to be tested is checked after. This implies that the statements within the loop block will be executed at least once. 31

Web Trainings Institute

Using For LOOP Here is what the for() loop looks like: PHP’s for() loop uses a counter that is initialized to a numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop, a conditional statement is tested. If it evaluates to true, the loop will execute once more and the counter will be incremented by 1 (or more) positions. If it evaluates to false, the loop will be broken and the lines following it will be executed instead. Example

Controlling Loop Iteration with break and continue The break keyword is used to exit a loop when it encounters an unexpected situation. A good example of this is the dreaded “division by zero” error—when dividing one number by another one (which keeps decreasing), it is advisable to check the divisor and use the break statement to exit the loop as soon as it becomes equal to zero. Here’s an example:

32

Web Trainings Institute

The continue keyword is used to skip a particular iteration of the loop and move to the next iteration immediately. This statement can be used to make the execution of the code within the loop block dependent on particular circumstances. The following example demonstrates by printing a list of only those numbers between 10 and 100 that are divisible by 12:

Array An array is a complex variable that enables you to store multiple values in a single variable; it comes in handy when you need to store and represent related information. An array variable can best be thought of as a “container” variable, which can contain one or more values. Here is an example: Creating an Array To define an array variable, name it using standard PHP variable naming rules and populate it with elements using the array() function, as illustrated in the following:
Web Trainings Institute

?> An alternative way to define an array is by specifying values for each element using index notation, like this:

In PHP, there are three kind of arrays:   

Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays

Numeric Arrays A numeric array stores each array element with a numeric index.There are two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("Saab","Volvo","BMW","Toyota"); 2. In the following example we assign the index manually: $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota";

34

Web Trainings Institute

Example In the following example you access the variable values by referring to the array name and index: The code above will output: Saab and Volvo are Swedish cars.

Associative Arrays An associative array, each ID key is associated with a value.When storing data about specific named values, a numerical array is not always the best way to do it.With associative arrays we can use the values as keys and assign values to them. Example 1 In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2 This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; The ID keys can be used in a script:
Web Trainings Institute

$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?> The code above will output: Peter is 32 years old. Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with automatically assigned ID keys: $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", 36

Web Trainings Institute

"Junior" ) ); The array above would look like this if written to the output: Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) ) Example 2 Lets try displaying a single value from the array above: echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; The code above will output:

37

Web Trainings Institute

Is Megan a part of the Griffin family? PHP Built-in Functions PHP Functions In this chapter we will show you how to create your own functions.To keep the browser from executing a script when the page loads, you can put your script into a function. The real power of PHP comes from its functions.In PHP, there are more than 700 built-in functions. A function will be executed by a call to the function. You may call a function from anywhere within a page. Create a PHP Function A function will be executed by a call to the function. Syntax function functionName() { code to be executed; } PHP function guidelines:  

Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a number)

Example A simple function that writes my name when it is called:
Web Trainings Institute

echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> Output: My name is Kai Jim Refsnes PHP Functions - Adding parameters To add more functionality to a function, we can add parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses. Example 1 The following example will write different first names, but equal last name: "; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); 39

Web Trainings Institute

?> Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes. Example 2 The following function has two parameters: "; } echo "My name is "; writeName("Kai Jim","."); echo "My sister's name is "; writeName("Hege","!"); echo "My brother's name is "; writeName("Ståle","?"); ?>

40

Web Trainings Institute

Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes? PHP Functions - Return values To let a function return a value, use the return statement. Example Output: 1 + 16 = 17

41

Web Trainings Institute

Grouping Form Selections with Arrays In addition to their obvious uses, arrays and loops also come in handy when processing forms in PHP. For example, if you have a group of related checkboxes or a multiselect list, you can use an array to capture all the selected form values in a single variable for greater ease in processing. To see how this works, create and run the following script: Select from the items below:
'; // use a foreach() loop to read and display array elements foreach ($_POST['options'] as $o) 42

Web Trainings Institute

{ echo "$o
"; } } else { echo 'Nothing selected'; } } ?> Notice in this script that the name of the Item price: '; // print number of rows affected echo mysql_affected_rows() . ' record(s) affected'; // close connection mysql_close($connection); 118

Web Trainings Institute

} ?> Here, the user is first presented with a form asking for an item and its associated price. Once the form is submitted, the form input is used inside to create an INSERT query, which is then sent to the database with the mysql_query() method. Because mysql_query() returns a Boolean indicating whether the query was successful, it is possible to check whether the INSERT took place and return an appropriate message. The previous example has three new functions: ■ The mysql_escape_string() function escapes special characters (like quotes) in the user input, so it can be safely entered into the database. If the magic_quotes_gpc setting in your PHP configuration file is enabled, you might need to first call stripslashes() on the user input before calling mysql_escape_string(), to avoid characters getting escaped twice. ■ The mysql_insert_id() function returns the ID generated by the previous INSERT query (useful only if the table into which the INSERT occurs contains an AUTO_INCREMENT field). ■ The mysql_affected_rows() function returns the total number of rows affected by the last operation. All these functions come in handy when dealing with queries that alter the database. Handling Errors Before you go out there and start building data-driven web sites, you should be aware that PHP’s MySQL API also comes with some powerful error-tracking functions that can reduce debugging time. Take a look at the following example, which contains a deliberate error in the SELECT query string:
Web Trainings Institute

if(!$result) { echo 'MySQL error ' . mysql_errno() . ': ' . mysql_error(); mysql_close($connection); } ?> The mysql_errno() function displays the error code returned by MySQL if there’s an error in your SQL statement, while the mysql_error() function returns the actual error message. Turn these both on, and you’ll find they can significantly reduce the time you spend fixing bugs. Using Ancillary Functions In addition to the functions discussed in previous sections, PHP’s MySQL API comes with a number of ancillary functions that may be used to find out more about the databases and tables on the MySQL server or to obtain server status information. Table 13-1 lists the important functions in this category. And here’s an example that demonstrates some of these functions in action: '; for ($x=0; $x
Web Trainings Institute

mysql_list_dbs() Returns a list of databases available on the MySQL server mysql_list_tables() Returns a list of tables available in a specified MySQL database mysql_list_fields() Returns information about the fields of a specified MySQL table mysql_stat() Returns status information about the MySQL server mysql_info() Returns information about the last executed query mysql_db_name() Returns a name of a database from the list generated by mysql_list_dbs() mysql_tablename() Returns a name of a table from the list generated by mysql_list_tables() mysql_ping() Tests the server connection

121

Web Trainings Institute

Working with HTML Forms Forms are a vital tool for the webmaster to receive information from the web surfer, such as: their name, email address, credit card, etc. A form will take input from the viewer and depending on your needs, you may store that data into a file, place an order, gather user statistics, register the person to your web forum, or maybe subscribe them to your weekly newsletter. Text Fields Before we teach you how to make a complete form, let's start out with the basics of forms. Input fields are going to be the meat of your form's sandwich. The has a few attributes that you should be aware of.    

type - Determines what kind of input field it will be. Possible choices are text, submit, and password. name - Assigns a name to the given field so that you may reference it later. size - Sets the horizontal width of the field. The unit of measurement is in blank spaces. maxlength - Dictates the maximum number of characters that can be entered.

HTML Code:
Name:
Password:
Input Forms: Name: Password: Do not use the password feature for security purposes. The data in the password field is not encrypted and is not secure in any way.

122

Web Trainings Institute

HTML Form Email Now we will add the submit functionality to your form. Generally, the button should be the last item of your form and have its name attribute set to "Send" or "Submit". Name defines what the label of the button will be. Here is a list of important attributes of the submit: In addition to adding the submit button, we must also add a destination for this information and specify how we want it to travel to that place. Adding the following attributes to your
will do just this.  

method - We will only be using the post functionality of method, which sends the data without displaying any of the information to the visitor. action - Specifies the URL to send the data to. We will be sending our information to a fake email address.

HTML Code: Name:
Password:
Email Forms: Name: Password: Send

HTML Radio Buttons Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires, and other web sites that give the user a multiple choice question. Below are a couple attributes you should know that relate to the radio button.  

value - specifies what will be sent if the user chooses this radio button. Only one value will be sent for a given group of radio buttons (see name for more information). name - defines which set of radio buttons that it is a part of. Below we have 2 groups: shade and size. 123

Web Trainings Institute

HTML Code:
What kind of shirt are you wearing?
Shade: Dark Light
Size: Small Medium Large
Radios: What kind of shirt are you wearing? Shade: Size:

Dark Small

Light Medium

Large

Email Myself

If you change the email address to your own and "Email Myself" then you should get an email with "shade=(choice) size=(choice)". HTML Check Boxes Check boxes allow for multiple items to be selected for a certain group of choices. The check box's name and value attributes behave the same as a radio button. HTML Code:
Select your favorite cartoon characters. Goofy Donald 124

Web Trainings Institute

Bugs Bunny Scooby Doo
Check Boxes: Select the 2 greatest toons. Goofy Donald Bugs Bunny Scooby Doo Email Myself

HTML Drop Down Lists Drop down menues are created with the is the list itself and each

PHP-MySQL Book.pdf

PHP-MySQL Book.pdf. PHP-MySQL Book.pdf. Open. Extract. Open with. Sign In. Main menu. Displaying PHP-MySQL Book.pdf.

1MB Sizes 25 Downloads 3884 Views

Recommend Documents

No documents