Intro to PHP

Download Report

Transcript Intro to PHP

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
<html>
<body>
<!- - Regular HTML -- >
<?php
//Your PHP goes here
?>
<!- - More HTML - ->
</html>
The difference is that a PHP file is executed by the Server
BEFORE being sent to the client. Just like CGI.
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);
Operators
Arithmetic: 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
Use any of:
include (“myLibraryFile.php”);
require(“myLibrary.php”);
require_once(“myLibrary.php”);
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 Continued
In every PHP program include the following as the
very 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
$_GET, $_POST, $_COOKIE
$_REQUEST
Purpose
Data sent between client
and server.
$_REQUEST includes all 3
$REMOTE_ADDR
$HTTP_REFERER
$REQUEST_TIME
IP of the client
Previous Web Page
When page was requested
(EPOCH time)
Browser Info
$HTTP_USER_AGENT
$_SERVER
Array of Server related
values
MYSQL FUNCTION CALL
mysql_error()
EXPLANATION
SQL Functions
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 database
returns 0 to n rows for SELECT
returns number of rows
affected for INSERT, UPDATE or
DELETE
$row=mysql_fetch_array($resu creates an associative array
lt)
using column names as keys
mysql_close($con)
closes the database connection
Some PHP Functions
date(‘r’)
EXPLANATION
SQL Functions
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