just a little php programming php on the server. common programming language features comments data...

Post on 19-Jan-2016

220 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Just a Little PHP

Programming PHP on the Server

Common Programming Language Features

• Comments• Data Types• Variable Declarations• Expressions• Flow of Control Statements• Functions and Subroutines• Macros and Preprocessor Commands• I/O Statements• Libraries• External Tools (Compiler, debugger etc)

PHP like JavaScript is Embedded in Web Pages

The difference is that a PHP file is executed by the Server BEFORE being sent to the client. Just like CGI.

<html> <body> <!- - Regular HTML -- > <?php

//Your PHP goes here ?> <!- - More HTML - -></html>

Comments

// This is a single line comment

/* This is a multiline comment just like C */

# works as a comment, just like the bash shell

Data Types

PHP is a weakly typed language.

Any variable can be any data type

The available data types are:

•boolean•number (integer and float)•string•array•object

Variable Names

To declare a scalar variable just use it.

Variable names begin with a $, ie:

$x=7;echo $counter;

#Assignment - all variables preceded by $ #whether on the left or the right$x=$myValue*2

Using Quotes

$x=‘The contents $var of this string are literally’;$y=“But $var is the value of the variable”;$z=`uptime`; #Run as a shell command, stored in $z$a=“Quoting in \$doubleQuotes \n<br>”;k

Constants

Numeric: 4.2 17.5 1.6E+7 21 0x2A

String: “Hello” ‘Nice Day’ Bob

define(“MYCONSTANT”, 42);

echo MYCONSTANT

If a constant is not defined it stands for itself, ie: Bob. Otherwise it stands for its value. Constants should be ALLCAPS and do not use a $ before the name

Creating an Array

$list[0] = 17; //This creates an array

$list = array(1,2,3 4,5); //creates an indexed array

$list = array(“Smith” => “Carpenter, “Jones”=> “Technician”, “Rajiv” => “Manager”); //Associative array

$n=sizeof($list);

OperatorsArithmetic: Regular C style operators

= + - * / % += -= *= /= ++ --

Relational: == != <> > < >= <= Note: “4” == 4 is True

String: “a” . $b $a.=$b;

Logical: && || !

Web Page Output

echo “The size of my array is: “ . $n;

print “Hello World: “ . $n;

printf “There are %4d items in my array, %s\n”, $n, $name;

printf uses the same format codes that C uses: %d (integer) %f (float) %x (hex) %s (string)

(There is one new format code: %b - binary)

Dumping an Array

print_r($anyArry);

#The entire array is dumped to the screen

if/then/else

if ($price <10 || $price>20){ printf “%10.2f is a reasonable price<br>”, $price; $total+=$price; }else echo “Try again!”;

switch

switch($choice){ case 1: case ‘beer’: doSomething(); ... break; case ‘prezels: doSomethingElse(); ... break; default: echo “Unknown option”;}

Simple for loops

for($i=1;$i<10;$i++){ $sum+=$i; echo “Running total is: “ + $sum + “<br>”; }

echo “Final total is: “ $sum;

Looping Through Associative Arrays

foreach( $array as $key => $value){ echo “Key: “ . $key echo “Value: “ . $value; }

Note: Associative Arrays and Indexed Arrays are the same thing. The key values for an indexed array are: 0, 1, 2 .....

Functions in PHP

function myFunction($arg1, $arg2, $arg3){ //Do some calculation ie:

$result= ($arg1 + $arg2) % $arg3;

return $result; }

Including a library of functions

include (“myLibraryFile.php”);

require(“myLibrary.php”);

require_once(“myLibrary.php”);

Use any of:

Debugging Php

In the same directory as your php program, include the file php.ini:

display_errors=on

A missing quote may result in a blank web page. Test your program for syntax error on the command line where it will show up:

$bash 3.2: php yourProg.php

Debugging ContinuedIn every PHP program include the following as thevery first commands:<?php ini_set(‘display_errors’,1); error_reporting(E_ALL); ...

?>

Strategies:•Always comment your code FIRST•Comment out blocks of code to isolate the error•Narrow down syntax errors to a single line.•Split complex lines into smaller stages•Use echo and printf statements liberally

Important PHP Variables Purpose$_GET, $_POST, $_COOKIE$_REQUEST

Data sent between client and server.$_REQUEST includes all 3

$REMOTE_ADDR IP of the client$HTTP_REFERER Previous Web Page $REQUEST_TIME When page was requested

(EPOCH time)

$HTTP_USER_AGENT Browser Info

$_SERVER Array of Server related values

SQL FunctionsMYSQL FUNCTION CALL EXPLANATION

mysql_error() Report on last error

mysql_connect(host,user, pass) connects to database; returns a connection to the database

mysql_selectdb(dbName) use specified schema

$result=mysql_query(stmt) runs stmt against the databasereturns 0 to n rows for SELECTreturns number of rows affected for INSERT, UPDATE or DELETE

$row=mysql_fetch_array($result)

creates an associative array using column names as keys

mysql_close($con) closes the database connection

SQL FunctionsSome PHP Functions EXPLANATION

date(‘r’) The current date as a string

time() current time

die(message) print out a message and quit

include(‘fileName’)require_once(‘fileName’);

include an external PHP file – allows shared code and libraries

header(‘attribute: value’) adds a header to the response

PHP Has A Rich Set of Library Functions

THE END

top related