Vous êtes sur la page 1sur 58

PHP

Personal Home Pages

PHP Hypertext Preprocessor


Rasmus Lerdorf
PHP version 3.0, June 6, 1998
Prof. Dr Milena Stankovi
Elektronski fakultet u Niu
E-mail:
mstankovic@elfak.ni.ac.yu
Elektronski fakultet u

ta je PHP

Server-side tehnologija koja obuhvata i poseban


script jezik

Script nardbe se ubacuje u HTML kod.

Script naredbama se dograuje HTML kod

PHP se obino koristi sa Apach serverom i


MySQL bayom podataka

Sve su to Open source tehnologije, to je bitno


uticalo na njihovu popularnost.
Elektronski fakultet u

PHP script instrukcije


<?
PHP Code In Here
?>
<?php
PHP Code In Here
php?>
<script language="php">
PHP Code In Here
</script>
Elektronski fakultet u

Prikaz informacija
Print
<?
print("Hello world!");
?>
Korienjem promenljive:
<?
$welcome_text = "Hello and welcome to my
website.";
print($welcome_text);
?>
Elektronski fakultet u

Formatiranje unutar script


instrukcije

U HTML obino koristimo:


<font face="Arial" color="#FF0000"> </font>
U PHP:
<font face=\"Arial\"
color=\"#FF0000\"></font>
print("<font face=\"Arial\"
color\"#FF0000\">Hello and welcome to my
website.</font>");
Klijentu e biti poslato samo:

<font face="Arial" color="#FF0000">Hello and


fakultet u
5
welcome to myElektronski
website.</font>

Upravljake strukture
IF naredba:
IF (something == something else)
{
THEN Statement
} else {
ELSE Statement
}
Primer:
if ($username == "webmaster") {
echo "Please enter your password below";
} else {
echo "We are sorry but you are not a
recognized user";
}
Elektronski fakultet u

Petlje

WHILE struktura primer:


$times = 5;
$x = 0;
while ($x < $times) {
echo "Hello World";
++$x;
}

Elektronski fakultet u

$names[0]
$names[1]
$names[2]
$names[3]
$names[4]

=
=
=
=
=

'John';
'Paul';
'Steven';
'George';
'David';

Polja

Primer korienja polja:


$number = 5;
$x = 0;
while ($x < $number) {
$namenumber = $x + 1;
echo "Name $namenumber is
$names[$x]<br>";
++$x;
}
Elektronski fakultet u

Polja i + operator
<?php
//define a couple of arrays
$a = array(
0=>"Apple",
2=>"Ball");
$b = array(
1=>"Cat", 2=>"Dog");
foreach(($a + $b) as
$key=>$value)
{ print("$key: $value<br>\n");
}
?>
Elektronski fakultet u

Rezultat:
0: Apple
2: Ball
1: Cat
Element 2 uzet
je iz niza a

Mail instrukcija
mail($to,$subject,$body,$headers);
Primer korienja:
$to = "php@gowansnet.com";
$subject = "PHP Is Great";
$body = "PHP is one of the best scripting languages
around";
$headers = "From: webmaster@gowansnet.com\n";
mail($to,$subject,$body,$headers);
echo "Mail sent to $to";

Elektronski fakultet u

10

function function_name(arguments)
{
code block
}

Funkcije

<?php
function printBold($text)
{
print("<b>$text</b>");
}
print("This Line is not Bold<br>\n");
printBold("This Line is Bold");
print("<br>\n");
print("This Line is not Bold<br>\n");
?>
Elektronski fakultet u

11

Funkcij koja vraa vrednost


<?
php function makeBold($text)
{
$text = "<b>$text</b>";
return($text);
}
print("This Line is not Bold<br>\n");
print(makeBold("This Line is Bold") .
"<br>\n"); print("This Line is not
Bold<br>\n");
?>
Elektronski fakultet u

12

Funkcij koja vraa referencu


<?php
function &getRandArray()
{
$a = array();
for($i=0; $i<10; $i++)
{ $a[] = rand(1,100); }
return($a);
}
$myNewArray = &getRandArray();
?>

Elektronski fakultet u

13

Lokalne i globalne promenljive

<?php
function assignName()
{
$name = "Zeev"; -- name je lokalna
promenljiva f-je
}
$name = "Leon"; -- name kao globalna
promenljiva
assignName();
//prints Leon
print($name);
prom
?>

-- tampa se vred- globalne

Elektronski fakultet u

14

Lokalne i globalne promenljive


<?
$capital = "Washington DC";
function Nation()
{
global $capital;
printCity($capital);
}
function printCity($NameOfCity)
{
print("The city is
$NameOfCity.<br>\n");
}
function California()
{
$capital = "Sacramento";
printCity($capital);
}

function Utah()
{
$capital = "Salt Lake
City";
printCity($capital);
}
Nation();
California();
Utah();

$capital =
Bie odtampano:
Beograd";
Nation(); Washington DC,
Sacramento,
?>

Salt Lake City,


d Washington DC

Elektronski fakultet u

15

Statike promenljive
<?
function useColor()
{
//remember the last color we
used static $ColorValue =
"#00FF00"; //choose the next
color if($ColorValue ==
"#00FF00")
{ $ColorValue = "#CCFFCC"; }
else
{ $ColorValue = "#00FF00"; }
return($ColorValue); }
Vrste tabele bie obojene
naizmenino u dve boje

print("<table width=\"300\">\n");
for($count=0; $count < 10;
$count++)
{
//get color for this row
$RowColor = useColor();
/* ** print out HTML for row **
set background color */
print("<tr>" .
"<td style=\"background:
$RowColor\">" .
"Row number $count" .
"</td>" .
"</tr>\n");
}
print("</table>\n"); ?>

Elektronski fakultet u

16

Dinamiki pozivi funkcija


<?php
function write($text)
{ print($text);
}
function writeBold($text)
{
print("<b>$text</b>");
}
$myFunction = "write";
$myFunction("Hello!");
print("<br>\n");
$myFunction = "writeBold";
$myFunction("Goodbye!");
print("<br>\n");
?>

Elektronski fakultet u

17

Klase i objekti
class Name extends Another
Class
{
Access Variable Declaration
Access Function Declaration
}

Elektronski fakultet u

18

Klase i objekti
primer klase

<?php
//define class for tracking users
class User
{
//properties
public $name;
private $password, $lastLogin;
//methods
public function __construct($name,
$password)
{
$this->name = $name;
$this->password = $password;
$this->lastLogin = time();
$this->accesses++;
}
// get the date of the last login
function getLastLogin()
{ return(date("M d Y", $this>lastLogin));
}
Elektronski
fakultet u
}

19

Klase i objekti
korienje klase
//create an instance
$user = new User("Leon", "sdf123");
//get the last login date
print($user>getLastLogin() ."<br>\n"); //print the
user's name
print("$user->name<br>\n");
?>

Elektronski fakultet u

20

Klase i objekti
Nasleivanje
<?php
class Animal
{
public $blood;
public $name;
public function __construct($blood,
$name=NULL)
{
$this->blood = $blood;
if($name) { $this->name = $name; }
}
}
Elektronski fakultet u

21

class Mammal extends Animal


{
public $furColor;
public $legs;
function __construct($furColor, $legs, $name=NULL)
{
parent::__construct("warm", $name);
$this->furColor = $furColor;
$this->legs = $legs;
}
}
class Dog extends Mammal
{
function __construct($furColor, $name)
{
parent::__construct($furColor, 4, $name); self::bark();
}
function bark()
{
print("$this->name says 'woof!'");
}
}
$d = new Dog("Black and Tan", "Angus");
Elektronski fakultet u
22
?>

Klase i objekti
Nasleivanje

Formulari
Primer formulara iz kojeg se podaci alju POST metodom:
<form action="mail.php" method="post">
Your Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br><br>
Comments<br>
<textarea name="comments"></textarea><br><br>
<input type="submit" value="Submit">
</form>

Elektronski fakultet u

23

PHP script koji prihvata podatke iz


formulara

<?
function checkOK($field)
{
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}
}
$name=$_POST['name'];
checkOK($name);
$email=$_POST['email'];
checkOK($email);
$comments=$_POST['comments'];
checkOK($comments);
$to=mstankovic@elfak.ni.ac.yu";
$message="$name just filled in your comments form. They
said:\n$comments\n\nTheir e-mail address was: $email";
if(mail($to,"Comments From Your Site",$message,"From: $email\n")) {
echo "Thanks for your comments.";
} else {
echo "There was a problem sending the mail. Please check that you filled in the
form correctly.";
}
Elektronski fakultet u
24
?>

Komentari
// Your comment can go in here
print "Hello $name"; // Welcome to the user
Komentar u vie linija:
/* The following piece of code will take the input
the user gave and will check that it is valid before
adding it to the database */

Elektronski fakultet u

25

Meanje PHP koda i HTML


<?
Top PHP code in here
?>
HTML Code
<?
Bottom PHP code in here
?>

<?
IF Statement {
?>
HTML For IF Being Correct
<?
} else {
?>
HTML For IF Being Wrong
<?
}
?>

<font face="Arial" size="7" color="red">


<b><? echo($variablename); ?></b></font>

Elektronski fakultet u

26

PHP- Pristup bazi podataka


PHP se najee koristi u sprezi sa MySQL
bazom podataka, mada se iy PHPa moe pristupiti
i drugim bazama kao to su SQL i ORACLE

Elektronski fakultet u

27

MySQL - tipovi polja


Field Type

Description

TINYINT

Small Integer Number

SMALLINT

Small Integer Number

MEDIUMINT Integer Number


INT

Integer Number

VARCHAR

Text (maximum 256 characters)

TEXT

Text
Elektronski fakultet u

28

Primer
Name Type

Length Description

id

INT

first

VARCHAR 15

Ime osobe

last

VARCHAR 15

Preyime

Jedinstveni identifikator sloga

phone VARCHAR 20

Broj telefona

mobile VARCHAR 20

Mobilni

fax

VARCHAR 20

fax

email

VARCHAR 30

e-mail adesa

web

VARCHAR 30

web adres

Elektronski fakultet u

29

Kreiranje tabele
<?
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="CREATE TABLE contacts (id int(6)NOT NULL
auto_increment,first varchar(15) NOT NULL,
last varchar(15) NOT NULL,phone varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,
email varchar(30) NOT NULL,web varchar(30) NOT NULL,
PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))";
mysql_query($query);
mysql_close();
?>

Elektronski fakultet u

30

Ubacivanje podataka u tabelu


First: John
Last: Smith
Phone: 01234 567890
Mobile: 00112 334455
Fax: 01234 567891
Email: johnsmith@gowansnet.com
Web: http://www.gowansnet.com
$query = "INSERT INTO contacts VALUES
('','John','Smith','01234 567890','00112 334455','01234
567891','johnsmith@gowansnet.com','http://www.gowansnet.com')
";
Elektronski fakultet u

31

Formular za popunjavanje tabele u bazi


<form action="insert.php" method="post">
First Name: <input type="text" name="first"><br>
Last Name: <input type="text" name="last"><br>
Phone: <input type="text" name="phone"><br>
Mobile: <input type="text" name="mobile"><br>
Fax: <input type="text" name="fax"><br>
E-mail: <input type="text" name="email"><br>
Web: <input type="text" name="web"><br>
<input type="Submit">
</form>

Elektronski fakultet u

32

Script za ubacivanje podataka u bazu


<?
$username="username";
$password="password";
$database="your_database";
$first=$_POST['first'];
$last=$_POST['last'];
$phone=$_POST['phone'];
$mobile=$_POST['mobile'];
$fax=$_POST['fax'];
$email=$_POST['email'];
$web=$_POST['web'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select
database");
$query = "INSERT INTO contacts VALUES
('','$first','$last','$phone','$mobile','$fax','$email','$web')";
mysql_query($query);
mysql_close();
?>

Elektronski fakultet u

33

Preuzimanje sloga iz baze


SELECT * FROM contacts
$query="SELECT * FROM contacts";
$result=mysql_query($query);
Preuzimanje vrednosti pojedinanih polja iz
sloga:
$variable=mysql_result($result,$i,"fieldname");
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
Elektronski fakultet u
34
$web=mysql_result($result,$i,"web");

Odbrojavanje slogova
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
CODE
$i++;
}

Elektronski fakultet u

35

Kompletan script za preuzimanje


podataka iz baze

<?
$username="username";
$password="password";
$database="your_database";

mysql_connect(localhost,$username,
$password);
@mysql_select_db($database) or die( "Unable
to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
Elektronski fakultet u

36

Kompletan script za preuzimanje


podataka iz baze - nastavak

echo "<b><center>Database Output</center></b><br><br>


$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
echo "<b>$first $last</b><br>Phone: $phone<br>Mobile:
$mobile<br>
Fax: $fax<br>E-mail: $email<br>Web: $web<br><hr><br>";
$i++;
}
?>

Elektronski fakultet u

37

Prikaz podataka u tabelu

<table border="0" cellspacing="2" cellpadding="2">


<tr>
<th><font face="Arial, Helvetica, sans-serif">Name</font></th>
<th><font face="Arial, Helvetica, sans-serif">Phone</font></th>
<th><font face="Arial, Helvetica, sans-serif">Mobile</font></th>
<th><font face="Arial, Helvetica, sans-serif">Fax</font></th>
<th><font face="Arial, Helvetica, sans-serif">E-mail</font></th>
<th><font face="Arial, Helvetica, sans-serif">Website</font></th>
</tr>

Elektronski fakultet u

38

Prikaz podataka u tabeluPreuzimanje pojedinanih vrednosti u


promenljive

<?
$i=0;
while ($i < $num) {

$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
?>
Elektronski fakultet u

39

Prikaz podataka u tabeliubacivanje podataka u vrstu tabele

<tr>
<td><font face="Arial, Helvetica, sans-serif">
<? echo $first." ".$last; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">
<? echo $phone; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">
<? echo $mobile; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">
<? echo $fax; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">
<a href="mailto:<? echo $email; ?>">E-mail</a></font></td>
<td><font face="Arial, Helvetica, sans-serif">
<a href="<? echo $web; ?>">Website</a></font></td>
</tr>
<?
$i++;
}
Elektronski fakultet u
echo "</table>" ?>;

40

Preuzimanje samo odreenih slogova iz baze


WHERE
SELECT * FROM contacts WHERE first='john'
$query="SELECT * FROM contacts WHERE
last='$searchlast'";
$result=mysql_query($query);
Izbor sloga na osnovu ID
SELECT * FROM contacts WHERE id='$id'

Elektronski fakultet u

41

ORDERED BY

SELECT * FROM contacts ORDER BY last ASC


Moe se koristiti i DESC

Elektronski fakultet u

42

GREKE
Baza je prazna
$num=mysql_numrows($result);
if ($num==0) {
echo "The database contains no contacts
yet";
} else {
Output Loop
}

Elektronski fakultet u

43

Inoviranje sadraja formulara


Preuzimanje sadraja iz baze:
Form Updata
$id=$_GET['id'];
$username="username";
$password="password";
$database="your_database";
mysql_connect(localhost,$username,
$password);
$query=" SELECT * FROM contacts WHERE
id='$id'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
Elektronski fakultet u

44

Inoviranje sadraja formulara


Form Updata
Prebacivanje vrednosti u promenljive:
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
Space For Code
++$i;
}
Elektronski fakultet u
45

Inoviranje sadraja formulara


Form Updata
Generisanje formulara sa preuzetim
vrednostima:
<form action="updated.php" method="post">
<input type="hidden" name="ud_id" value="<? echo $id; ?>">
First Name: <input type="text" name="ud_first" value=
<? echo $first; ?>"><br>
Last Name: <input type="text" name="ud_last" value=
<? echo $last; ?>"><br>
Phone Number: <input type="text" name="ud_phone" value=
<? echo $phone; ?>"><br>
Mobile Number: <input type="text" name="ud_mobile" value=
<? echo $mobile; ?>"><br>
Fax Number: <input type="text" name="ud_fax" value=
<? echo $fax; ?>"><br>
E-mail Address: <input type="text" name="ud_email" value=
<? echo $email; ?>"><br>
Web Address: <input type="text" name="ud_web" value=
<? echo $web; ?>"><br>
<input type="Submit" value="Update">
</form>
Elektronski fakultet u
}

46

UPDATE baze - primer


Preuzimanje podataka iz formulara:
$ud_id=$_POST['ud_id'];
$ud_first=$_POST['ud_first'];
$ud_last=$_POST['ud_last'];
$ud_phone=$_POST['ud_phone'];
$ud_mobile=$_POST['ud_mobile'];
$ud_fax=$_POST['ud_fax'];
$ud_email=$_POST['ud_email'];
$ud_web=$_POST['ud_web'];

Elektronski fakultet u

47

UPDATE baze - primer


Konekcija sa bazom:
$username="username";
$password="password";
$database="your_database";
mysql_connect(localhost,$username,
$password);

Elektronski fakultet u

48

UPDATE baze - primer


Generisanje upita:
$query="UPDATE contacts SET
first='$ud_first', last='$ud_last',
phone='$ud_phone', mobile='$ud_mobile',
fax='$ud_fax', email='$ud_email',
web='$ud_web' WHERE id='$ud_id'";
mysql_query($query);
echo "Record Updated";
mysql_close();

Elektronski fakultet u

49

Inoviranje sadraja baze


UPDATE
Upit:
$query = "UPDATE contacts SET first =
'$ud_first', last = '$ud_last', phone =
'$ud_phone', mobile = '$ud_mobile', fax =
'$ud_fax', email = '$ud_email', web =
'$ud_web' WHERE id = '$ud_id'";

Elektronski fakultet u

50

Korienje petlji sa UPDATE


$query=" SELECT * FROM contacts WHERE
last='Smith'";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$query1="UPDATE contacts SET
web='http://www.smith.com' WHERE id='$id'";
mysql_query($query);
++$i;
}
mysql_close(); Elektronski fakultet u
51

UPDATE
$query1="UPDATE contacts SET
web='http://www.smith.com' WHERE
last='Smith'";

Elektronski fakultet u

52

UPRAVLJANJE SESIJAMA
Web sesija je vreme koje korisnik provede na jednom sajtu
koristei pri tome istu istancu itaa. Ako korisnik zatvori ita
(ili eksplicitno napusti sesiju) tada promenljive sesije nisu vie
pridruene tom korisniku.
U php.ini fajlukoji se nalazi u c:\windows treba podesiti:
session.save_path = C:/temp

Elektronski fakultet u

53

UPRAVLJANJE SESIJAMA
Primer
<?
session_start();
if(!isset($count)) {
session_register("count");
$count = 1;
}
?>
You have been to this page <?=$count?>
times.
<?
$count++;
?>
Elektronski fakultet u

54

1. <?
2. session_start();
3. session_register("first");
4. session_register("last");
5. session_register("email");
6. session_register("news_prefs");
7. ?>
8. <html>
9. <head>
10. <title>Welcome</title>
11. <style type="text/css">
12. p, ul, h3 {font-family: verdana, helvetica,
sans-serif;}
13. .enabled {font-weight: bold; color: green;}
14. .disabled {font-weight: bold; color: red;}
15. </style>
16. </head>
17. <body>
18. <?
19. function load_user_data(){
20. global $first,
$last, $email,
$news_prefs;
Elektronski
fakultet
u

UPRAVLJANJE SESIJAMA
Primer

55

UPRAVLJANJE SESIJAMA
21. $first = "Faye";
Primer
22. $last = "Valentine";
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.

$email = "faye@bebop.com";
$news_prefs = array(
"Local" => 0,
"Nation" => 1,
"World" => 1,
"Comics" => 0,
);
}
load_user_data();
?>
<h3>Welcome</h3>
<p>Welcome back <b><?=$first?
></b>
35. <p>Your settings have been loaded.
36. <p><a href=track_prefs2.php>View
Your Settings</a>.
37. </body>
Elektronski fakultet u
38. </html>

56

1.
2.
3.
4.
5.
6.
7.
8.

UPRAVLJANJE SESIJAMA
Primer

<?
session_start();
?>
<html>
<head>
<title>View Settings</title>
<style type="text/css">
p, ul, h3 {font-family: verdana, helvetica,
sans-serif;}
9. .enabled {font-weight: bold; color: green;}
10. .disabled {font-weight: bold; color: red;}
11. </style>
12. </head>
13. <body>
14. <h3>View
Your Settings</h3>
Elektronski
fakultet u
57

UPRAVLJANJE SESIJAMA
16. <p>Email: <?=$email?>
Primer
17. <p>Your settings:<ul>
18. <?
19. while(list($key,$value) =
each($news_prefs)) {
20. if($value) {
21. $value = "Enabled";
22. } else {
23. $value = "Disabled";
24. }
25. print("<li class=$value>$key:
$value</li>");
26. }
27. ?>
28. </ul>
29. </body>
Elektronski fakultet u
30. </html>

58

Vous aimerez peut-être aussi