You are on page 1of 61

PHP & MYSQL

Down the rabbit hole

Server-side
A server is a software program, such as a web server, that runs on a remote server, reachable from a user's local computer or workstation. Server-side refers to operations that are performed by the server in a clientserver relationship in computer networking. Operations may be performed server-side because they require access to information or functionality that is not available on the client, or require typical behavior that is unreliable when it is done client-side.

Server-side Scripting
Server-side scripting is a web server technology in which a user's request is fulfilled by running a script directly on the web server to generate dynamic web pages It is usually used to provide interactive web sites that interface to databases or other data stores. Almost every major web site uses some amount of server-side scripting.

The Story of PHP


PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP. PHP was conceived sometime in the fall of 1994 by Rasmus Lerdorf. Personal Home Page Tools PHP 3.0 was developed by Andi Gutmans and Zeev Suraski. PHP 3.0 supports MySQL and Oracle. PHP 4.0 was released PHP 5 was released on 2004

Features
Simplicity Portability Speed Open Source Extensible XML and Database Support

The Story of MySQL


MySQL is a database server It is a high-performance, multiuser RDMS. Owned by MySQLAB also known as TcX MySQL is ideal for both small and large applications MySQL supports standard SQL The most popular open-source database

Continuation
MySQLs customers: Yahoo!, Google, Cisco, NASA and HP. Designed around three fundamental principles:
Speed Stability Ease

of use

Features
Speed Reliability Security Scalability Portability Ease of use Compliance with existing standards (ANSI SQL-99) Wide Application Support Free

How PHP works?

Client

Things you need


OS Apache Server PHP 5 MySQL Sample platforms:
LAMP WAMP MAMP

Lets get started!


A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. Sample code:
<html> <body> <?php echo "Hello World"; ?> </body> </html>

Comment Please?
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. Sample comment: <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>

Take note Please?


Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. semi-colon is not needed to terminate the last line of a PHP block The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed. Blank lines within the PHP tags are ignored by the parser Everything outside the tags is also ignored by the parser, and returned as-is

Variables
PHP supports a number of different variable types: integers, floating point numbers, strings and arrays It automagically determines variable type by the context in In PHP, a variable name is preceded by a dollar ($) symbol and must begin with a letter or underscore, optionally followed by more letters, numbers and/or underscores. which it is being used. Note that variable names in PHP are case sensitive, so $me is different from $Me or $ME.

Variable Demo
<html> <head></head> <body> Agent: So who do you think you are, anyhow? <br /> <?php // define variables $name = 'Neo'; $rank = 'Anomaly'; $serialNumber = 1; // print output echo "Neo: I am <b>$name</b>, the <b>$rank</b>. You can call me by my serial number, <b>$serialNumber</b>."; ?> </body> </html>

Using Operators
Arithmetic Comparison Logical String Auto-Increment and Auto-decrement

Arithmetic Operators
Assignment (=) Addition (+) Subtraction (-) Multiplication (*) Division ;returns quotient (/) Division; returns modulus (%)

Sample Code
<?php // define variables $num1 = 101; $num2 = 5; // add $sum = $num1 + $num2; // subtract $diff = $num1 - $num2;

Sample Code
// multiply $product = $num1 * $num2; // divide $quotient = $num1 / $num2; // modulus $remainder = $num1 % $num2; ?>

Tips
To perform an arithmetic operation simultaneously with an assignment, use the two operators together. The following two code snippets are equivalent: <?php $a = $a + 10; ?> <?php $a += 10; ?>

Comparison Operators
Equal to (==) Equal to and of the same type (===) Not equal to or not of the same type (!==) Not equal to (<> aka !=) Less than (<) Less than or equal to (<=) Greater than (>) Greater than or equal to (>=)

Sample Codes
<?php // define some variables $mean = 29; $median = 40; $mode = 29; // less-than operator $result = ($mean < $median);

Sample Codes
// greater-than operator $result = ($mean > $median); // less-than-or-equal-to operator $result = ($median <= $mode); // greater-than-or-equal-to operator $result = ($median >= $mode);

Sample Codes
// equality operator $result = ($mean == $mode); // not-equal-to operator $result = ($mean != $mode); // inequality operator $result = ($mean <> $mode); ?>

String Operator
String Concatenation (.) Sample Code: <?php $username = 'john'; $domain = 'example.com'; // combine them using the concatenation operator $email = $username . '@' . $domain; ?>

Tips
You can concatenate and assign simultaneously, as in the following: <?php // define string $str = 'the'; // add and assign $str .= 'n'; // $str now contains "then" ?>

Logical Operators
Logical AND (&&) Logical OR (||) Logical XOR (xor) Logical NOT (!)

Sample Codes
<?php // define some variables $user = 'joe'; $pass = 'trym3'; $saveCookie = 1; $status = 1; // logical AND $result = (($user == 'joe') && ($pass == 'trym3'));

Sample Codes
// logical OR $result = (($status < 1) || ($saveCookie == 0)); // logical NOT $result = !($saveCookie == 1); // logical XOR $result = (($status == 1) xor ($saveCookie == 1)); ?>

Auto-increment and Auto-decrement


Addition by 1 (++) Subtraction by 1 (--)

Sample Codes
<?php // define $total as 10 $total = 10; // increment it $total++; // $total is now 11 ?> Thus, <?php $total++; ?> is functionally equivalent to <?php $total = $total + 1; ?>. Theres also a corresponding auto-decrement operator (--), which does exactly the opposite:

Sample Codes
<?php // define $total as 10 $total = 10; // decrement it $total--; // $total is now 9 ?>

Using the if() statement


<?php if (conditional test) { do this; } ?>

Sample Codes
<?php if ($temp >= 100) { echo 'Very hot!'; } ?>

If-else() Statement
<?php if (conditional test) { do this; } else { do this; } ?>

Sample Codes
<?php if ($temp >= 100) { echo 'Very hot!'; } else { echo 'Within tolerable limits'; } ?>

More than one way to kill a Chicken


<?php if ($elvis == 0) { echo 'Elvis has left the building!'; } else { echo 'Elvis is still backstage!'; } ?> <?php if ($elvis == 0): echo 'Elvis has left the building!'; else: echo 'Elvis is still backstage!'; endif; ?>

If-else-if()Statement
<?php if (conditional test #1) { do this; } elseif (conditional test #2) { do this; } else { do this; } ?>

Sample Code
<?php if ($country == 'UK') { $capital = 'London'; } elseif ($country == 'US') { $capital = 'Washington'; } else { $capital = 'Unknown'; } ?>

Switch()Statement
<?php switch (condition variable) { case possible result #1: do this; case possible result #2: do this; ... case possible result #n: do this; case default; do this; } ?>

Sample Code
<?php switch ($country) { case 'UK': $capital = 'London'; break; case 'US': $capital = 'Washington'; break; default: $capital = 'Unknown'; break; } ?>

Repeating actions with loops


A loop is a control structure that enables you to repeat the same set of statements or commands over and over again The actual number of repetitions may be dependent on a number you specify, or on the fulfillment of a certain condition or set of conditions. While Loop Do While Loop For Loop

While Loop
The first and simplest loop to learn As long as the conditional expression specified evaluates to true, the loop will continue to execute. <?php while (condition is true) { do this; } ?>

Sample Code
<?php // define number and limits for multiplication tables $num = 11; $upperLimit = 10; $lowerLimit = 1; // loop and multiply to create table while ($lowerLimit <= $upperLimit) { echo "$num x $lowerLimit = " . ($num * $lowerLimit); $lowerLimit++; } ?>

Do While Loop
You might need to execute a set of statements at least once, regardless of how the conditional expression evaluates. <?php do { do this; } while (condition is true) ?>

PHP Function
A function is simply a set of program statements that perform a specific task, and that can be called, or executed, from anywhere in your program. Syntax:

function functionName() { code to be executed; }

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

Sample Function
<?php // define a function function displayShakespeareQuote() { echo 'Some are born great, some achieve greatness, and some have greatness thrust upon them'; } // invoke a function echo Shakespeare said . displayShakespeareQuote(); ?>

Function with arguments


<?php // define a function // with a single-argument list function convertMilesToKilometres($miles) { echo "$miles miles = " . $miles * 1.60 . " km"; } // invoke a function // pass it a single argument convertMilesToKilometres(50); ?>

Function that returns value


<?php // define a function function getTriangleArea($base, $height) { $area = $base * $height * 0.5; return $area; } // invoke a function echo 'The area of a triangle with base 10 and height 50 is ' . getTriangleArea(10, 50); ?>

List() function
The list() function is used to assign values to a list of variables in one operation. Syntax list(var1,var2...)

List() function sample


<?php // define an array $flavors = array('strawberry', 'grape', 'vanilla'); // extract values into variables list ($flavor1, $flavor2, $flavor3) = $flavors; echo $flavor1; ?>

List() function sample


<?php $my_array = array("Dog","Cat","Horse"); list($a, $b, $c) = $my_array; echo "I have several animals, a $a, a $b and a $c."; ?>

Explode() function
The explode() function breaks a string into an array. Splits a string into smaller components on the basis of a user-specified pattern, and then returns these elements as an array. Syntax explode(separator,string,limit)

Explode() function sample


<?php // define string $string = 'English Latin Greek Spanish'; // split on whitespace $languages = explode(' ', $string); // $languages now contains ('English', 'Latin', 'Greek', 'Spanish') ?>

Explode() function sample


<?php $str = "Hello world. It's a beautiful day."; echo explode(" ",$str); ?>

Implode() function
The implode() function returns a string from the elements of an array. Syntax implode(separator,array) Sample: <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?>

PHP include() Function


The include() function takes all the content in a specified file and includes it in the current file. If an error occurs, the include() function generates a warning, but the script will continue execution.

Include() function sample


<html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html>

Include() function sample


<?php // import file include("/path/to/user/defined/functions.php"); // invoke functions here ?>

Include() function sample


Assume we have a standard menu file, called "menu.php", that should be used on all pages: <a href="/default.php">Home</a> <a href="/tutorials.php">Tutorials</a> <a href="/references.php">References</a> <a href="/examples.php">Examples</a> <a href="/about.php">About Us</a> <a href="/contact.php">Contact Us</a>

Include() function sample


<html> <body> <div class="leftmenu"> <?php include("menu.php"); ?> </div> <h1>Welcome to my home page.</h1> <p>Some text.</p> </body> </html>

You might also like