PHP 2
PHP 2
What is PHP?
Interpreted language, scripts are parsed at runtime rather than compiled beforehand
Executed on the server-side
Source-code not visible by client
?>
Comments in PHP
Variables in PHP
Variable usage
<?php
$foo = 25;
$bar = Hello;
$foo = ($foo * 7);
$bar = ($bar * 7);
?>
// Numerical variable
// String variable
// Multiplies foo by 7
// Invalid expression
Echo
Syntax
Echo example
<?php
$foo = 25;
$bar = Hello;
echo
echo
echo
echo
echo
?>
$bar;
$foo,$bar;
5x5=,$foo;
5x5=$foo;
5x5=$foo;
// Numerical variable
// String variable
//
//
//
//
//
Outputs
Outputs
Outputs
Outputs
Outputs
Hello
25Hello
5x5=25
5x5=25
5x5=$foo
Notice how echo 5x5=$foo outputs $foo rather than replacing it with 25
Strings in single quotes ( ) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as
\n or \\)
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print <p><h1>$total</h1>;
// total is 45
?>
$a - $b
$a * $b
$a / $b
$a += 5
// subtraction
// multiplication
// division
// $a = $a+5 Also works for *= and /=
Concatenation
Hello PHP
Computer Science
If ... Else...
If (condition)
<?php
If($user==John)
{
{
Print Hello John.;
Statements; }
Else
}
{
Print You are not John.;
Else
}
?>
{
Statement;
No THEN in PHP
}
<?php
$number = 42;
if($number == 42)
echo "The number is 42!";
?>
<?php
$animal = "Cat";
if($animal == "Dog")
echo "It's a dog!";
else
echo "I'm sure it's some sort of animal, but
not a dog!"
?>
While Loops
While (condition)
{
Statements;
}
<?php
$count=0;
While($count<3)
{
Print hello PHP. ;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>
Include Files
Include opendb.php;
Include closedb.php;
This inserts files; the code in files will be inserted into current code.
This will provide useful and protective means once you connect to a
database, as well as for other repeated functions.
Include (footer.php);
The file footer.php might look like:
<hr SIZE=11 NOSHADE WIDTH=100%>
<i>Copyright 2008-2010 KSU </i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.kent.edu</i></font><br>
Including files
One of the most popular features of PHP is the ability to include files. This
allows you to separate your code into multiple files, and re-use them in
.
<i>Below this, content will come from another
file!</i> <br /><br /><br /> <?php $number1
= 20; include("includedfile.php"); ?> <br /><br
/><br /> <i>We're back, after the included file
has ended!</i>
various places
Including files
Multidimensional arrays
Sorting arrays
Date Display
2009/4/1
$datedisplay=date(yyyy/m/d);
Print $datedisplay;
# If the date is April 1st, 2009
# It would display as 2009/4/1
$datedisplay=date(l, F m, Y);
Print $datedisplay;
# If the date is April 1st, 2009
# Wednesday, April 1, 2009
Jan
January
01
1
d
J
l
D
01
1
Monday
Mon
Functions
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
$result_1 = foo(12, 3);
echo $result_1;
echo foo(12, 3);
?>
Data types
To create a class, you need to use the keyword class followed by the name
of the class. The name of the class should be meaningful to exist within the
system (See note on naming a class towards the end of the article). The
body of the class is placed between two curly brackets within which you
declare class data members/variables and class methods.
<?php
class User
{ } ?>
Class structure
class <class-name>
{ <class body :- Data Members &
Methods>; }
class User {
public $name;
public $age;
public function Describe()
{ return $this->name . " is " . $this->age . "
years old"; }
}
$user = new User(); $user->name = "John Doe"; $user->age = 42;
echo $user->Describe();
Public
Public Example
<?php
Class person{
Public function getName()
{
return Mahandra;
}
}
?>
<?php
$p = new person ();
echo $p->getName();
?>
?>
Private
<?php
Class person{
Public function firstName()
{
return Mahandra;
}
Privite function LastName()
{
ReturnJames;
}
}
?>
<?php
$p = new person ();
echo $p->firstName();
echo $p->LastName();
?>
Protected
Constructors and
destructors
construct
Destructors
Destructors
Visibility
Visibility
Inheritance
class Animal {
public $name;
public function Greet()
{ return "Hello, I'm some sort of animal and my name is " . $this->name;
}
}
class Dog extends Animal {
public function Greet()
{ return "Hello, I'm a dog and my name is " . $this->name; }
}
$animal = new Animal(); echo $animal->Greet(); $animal = new Dog();
$animal->name = "Bob"; echo $animal->Greet();
Abstract classes
Static classes
Since a class can be instantiated more than once, it means that the
values it holds, are unique to the instance/object and not the class
itself. This also means that you can't use methods or variables on a
class without instantiating it first, but there is an exception to this
rule. Both variables and methods on a class can be declared as
static (also referred to as "shared" in some programming
languages), which means that they can be used without instantiating
the class first. Since this means that a class variable can be
accessed without a specific instance, it also means that there will
only be one version of this variable. Another consequence is that a
static method cannot access non-static variables and methods,
since these require an instance of the class.
Class constants
Overloading
Image.php
<?php
class Image {
function __construct() {
echo 'Class Image loaded successfully <br />';
}
}
?>
Test.php
<?php
class Test {
function __construct() {
echo 'Class Test working <br />';
}
}
?>
Index.php
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$a = new Test();
$b = new Image();
?>
throw exception
<?php
function __autoload($class_name) {
if(file_exists($class_name . '.php')) {
require_once($class_name . '.php');
} else {
throw new Exception("Unable to load $class_name.");
}
}
try {
$a = new Test();
$b = new Image();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
PHP - Forms
Access to the HTTP POST and GET data is simple in
PHP
The global variables $_POST[] and $_GET[] contain the
request data
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="cancel" value="Cancel">
</form>
http://www.cs.kent.edu/~nruan/form.php
WHY
PHP
Sessions
?
Whenever you want to create a website that allows you to store
PHP - Sessions
Sessions store their identifier in a cookie in the clients browser
Every page that uses session data must be proceeded by the
session_start() function
Session variables are then set and retrieved by accessing the
global $_SESSION[]
Save it as session.php
<?php
session_start();
if (!$_SESSION["count"])
$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";
?>
<a href="session.php?count=yes">Click here to count</a>
http://www.cs.kent.edu/~nruan/session.php
Error!
Warning: Cannot send session cookie - headers already
sent by (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3
Warning: Cannot send session cache limiter - headers
already sent (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3
PHP Overview
Easy learning
Syntax Perl- and C-like syntax. Relatively
easy to learn.
Large function library
Embedded directly into HTML
Interpreted, no need to compile
Open Source server-side scripting language
designed specifically for the web.
Save as sample.php:
<! sample.php -->
<html><body>
<?php
$myvar = "Hello World";
echo $myvar;
?>
</body></html>
http://www.cs.kent.edu/~nruan/sample.php
second.php
showtable.php
second.php
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
// change the value of $dbuser and $dbpass to your username and password
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = *****************;
$dbname = $dbuser;
$table = 'account';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbname))
die("Can't select database");
second.php (cont.)
$result = mysql_query("SHOW TABLES");
if (!$result) {
die("Query to show fields from table failed");
}
$num_row = mysql_num_rows($result);
echo "<h1>Choose one table:<h1>";
echo "<form action=\"showtable.php\" method=\"POST\">";
echo "<select name=\"table\" size=\"1\" Font size=\"+2\">";
for($i=0; $i<$num_row; $i++) {
$tablename=mysql_fetch_row($result);
echo "<option value=\"{$tablename[0]}\" >{$tablename[0]}</option>";
}
echo "</select>";
echo "<div><input type=\"submit\" value=\"submit\"></div>";
echo "</form>";
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
showtable.php
<html><head>
<title>MySQL Table Viewer</title>
</head>
<body>
<?php
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = **********;
$dbname = 'nruan';
$table = $_POST[table];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) die("Query to show fields from table failed!" . mysql_error());
showtable.php (cont.)
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
Functions Covered
mysql_connect()
include()
mysql_query()
mysql_fetch_array()
mysql_select_db()
mysql_num_rows()
mysql_close()
History of PHP
PHP References