Beruflich Dokumente
Kultur Dokumente
XML Style
<?php
Short Style
<?
?>
?>
Script Style
<script language=php>
</script>
ASP Style
<%
%>
<?php
echo hello,$name.;
?>
\n
\r
\t
\\
\s
\
Linefeed
Carriage return
Horizontal tab
Backslash
Dollar sign
Double quote
<html>
<body>
<?php
//This is a comment
/*This
is a
commentblock*/
?>
</body>
</html>
Naming Rules:
prefixed
with a $
begin with letter or underscore
may contain only letters, number,
underscores
case sensitive
$distance
$a
descriptive
a
with $
$123abc
or
$x+y
valid
valid but not
not valid, must start
not valid, $ must be
followed by letter
underscore
not valid
<?php
$txt="Hello World!";
x=16;
?>
<?PHP
$firstname=jeeva;
echo $firstname;
?>
echo( );
allows you to send one or multiple
pieces of code, separated by commas
<?php
echo "<h2>PHP is fun!</h2>";
echo "I'm about to learn PHP!<br>";
?>
print( );
returns a value of TRUE or FALSE, if the
function was called successfully
<?php
$firstname=jeeva;
print $firstname;
?>
Strings
Integers
floating-point
Boolean
Array
Object
Operator
+
*
/
quotient
%
modulus
Description
Add
Subtract
Multiply
Divide and return
Divide and return
<?php
$x=10;
$y=6;
echo ($x + $y); // outputs 16
echo ($x - $y); // outputs 4
echo ($x * $y); // outputs 60
echo ($x / $y); // outputs
1.6666666666667
echo ($x % $y); // outputs 4
?>
Operator Description
==
Equal to
!=
Not equal to
> Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
=== Equal to and of the same type
<?php
$p = 10;
$q = 11;
$r = 11.3;
$s = 11;
echo ($q > $p);
echo ($q < $p);
echo ($q >= $s);
echo ($r <= $s);
echo ($q == $s);
echo ($q == $r);
?>
Operator
Description
&&
||
!
AND
OR
NOT
<?php
$price = 100;
$size = 18;
echo ($price > 50 && $size < 25);
echo ($price > 150 || $size > 75);
echo !($size > 10);
?>
Operator Description
+=
Add and assign
-=
Subtract and assign
*=
Multiply and assign
/= Divide and assign quotient
%= Divide and assign modulus
.=
Concatenate and
assign (strings only)
<?php
$count = 7;
$age = 60;
$greeting = 'We';
$count -= 2;
echo $count;
$age;
echo $age;
$greeting .= 'lcome!';
echo $greeting;
?>
<?php
$name=venkat";
if($name==venkat")
{
echo venkat become software
engineer";
}
?>
<?php
$name=hopes";
if($name==venkat")
{
echo venkat become software engineer";
}
else
{
echo "you enter name is wrong";
}
?>
Syntax
if( condition1 )
{
statement1;
}
elseif ( condition2 )
{
statement2;
}
else
{
statement3;
}
<?php
$name="sitra";
if($name=="hopes")
{
echo "hopes college";
}
else if($name=="sitra")
{
echo "you enter place is sitra";
}
else
{
echo "you enter wrong places";
}
?>
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
...
default:
code to be executed if n is different from all labels;
}
<?php
$position="dba";
switch($position)
{
case "member":
echo "Welcome Member";
break;
case "siteadmin":
echo "Welcome siteadmin";
break;
case "designer":
echo "Welcome Designer";
Break;
case "dba":
echo "Welcome dba";
break;
default:
echo "Welcome you all others ";
break;
}
?>
While statements
The while statement will execute a
block of code if and as long as a
condition is true.
Syntax
while (condition)
{ code to be executed;
}
<?php
$count=1;
while($count<=10)
{
echo "$count<br/>";
$count++;
}
<?php
$counter=0;
do
{
$counter++;
echo "The number is " . $counter . "<br />";
}
while($counter<5);
?>
<?php
for($i=0;$i<5;$i++)
{
echo "welcome to php<br/>";
}
?>
Syntax
foreach($arrayName as $value)
{
statements;
<?php
$employeeAges;
$employeeAges["Lisa"]="28";
$employeeAges["Jack"]="16";
$employeeAges["Ryan"]="35";
$employeeAges["Rachel"]="46";
$employeeAges["Grace"]="34";
foreach($employeeAges as $key => $value)
{
echo "Name: $key, Age: $value <br />";
}
?>
Strlen()
The strlen() function returns the length of
a string.
Syntax
strlen(string)
Example
<?php
echo strlen(Raju);
?>
Strcmp()
The strcmp() function compares two
strings.
Syntax
strcmp(string1, string2);
Example
<?php
echo strcmp(Raj",Raj");
?>
Strrev()
The strrev() function reverses a string.
Syntax
strrev(string);
Example
<?php
echo strrev("Hello World!");
?>
Strtrim()
Remove leading and trailing whitespace from a string.
Syntax
trim(string,charlist);
Example
<?php
$str = ' a b c ';
echo trim($str);
// output 'a b c
?>
Substr()
Retrieves a section of strings.
Syntax
substr(string,start,length);
Example
<?php
$str = 'Welcome to nowhere';
echo substr($str, 3, 4);
//output: come
?>
Strtolower()
Lowercases a string.
Syntax
strtolower(string);
Example
<?php
$str = 'Yabba Dabba Doo';
echo strtolower($str);
// output: 'yabba dabba doo
?>
Strtoupper()
uppercases a string.
Syntax
strtoupper(string);
Example
<?php
$str = 'Yabba Dabba Doo';
echo strtoupper($str);
// output: 'YABBA DABBA DOO
?>
Round()
The round() function rounds a floating-point
number.
Syntax
round(number,precision,mode);
Example
<?php
echo(round(4.96754,2) . "<br>");
echo(round(7.045,2) . "<br>");
echo(round(7.055,2));
?>
Number_format()
The number_format() function formats a number with
grouped thousands.
Syntax
number_format(number,decimals,decimalpoint,separator) ;
Example
<?php
$num = 1999.9;
$formattedNum = number_format($num)."<br>";
echo $formattedNum;
$formattedNum = number_format($num, 2);
echo $formattedNum;
?>
function multiply($n1,$n2)
{
$product=$n1*$n2;
return $product;
}
$x=3;
$y=4;
$z=multiply($x,$y);
echo "$z";
<?php
if(!isset($_POST['submit']))
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter your age: <input name="age" size="2">
<input type="submit" name="submit" value="Go">
<?
}
else
{
$input = $_POST['age'];
if($input < 27)
{
echo "You are young";
}
elseif($input == 27)
{
echo "The perfect age";
}
elseif($input > 27)
{
echo "You are old!";
}
}
?>
Definitions
Unlike strings, which hold a single value,
arrays hold a list of values, also called
elements. Each value can be a string,
number, or another array.
An array is a special variable, which can
hold more than one value at a time.
For each value in the list, there is a key
or index associated with it.
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] .
" and " . $cars[2] . ".";
?>
Indexed Arrays
Arrays with numeric keys
Associative Arrays
Arrays with named keys.
Multidimensional Arrays
Arrays containing one or more
arrays
<?php
$places=array("ukkadam","lakshmi_mills","PS
G","HOPES
","KICE");
$places[0]="ukkadam";
for($x=0;$x<count($places);$x++)
{
echo "{$places[$x]}<br />";
}
//echo $places[0]. " " .$places[1];
?>
<?php
$age=array("jeeva"=>32,"jaik"=>22,"
sudhar"=>25);
//echo "sudhar age is " . $age["sudhar"]
. "years old.";
echo $age["jeeva"];
?>
$red=array("r1","r2","r3","r4");
$green=array("g1","g2","g3","g4");
$blue=array("b1","b2","b3","b4");
$colrs=array("Red"=>$red,
"Green"=>$green,
"Blue"=>$blue);
print $colrs['Green'][0];
gettimeof day()
The gettimeofday() function returns the
current time.
<?php
// Print the array from gettimeofday()
print_r(gettimeofday());
?>
$b=time();
print date("m/d/y",$b)."<br/>";
print date("D,F jS",$b)."<br/>"; //D-mon FSeptember jS-21st
print date("l,F jS Y",$b)."<br/>"; //llowercase fullday, Y-year
print date("g:i A",$b)."<br/>";//g-12hours
format,A-Am or Pm
print date("r",$b)."<br/"; //RFC 822
formatted date; Mon, 21 Sep 2010 time
+200
<?php
$color=green;
$fruit=apple;
?>
<?php
echo A $color $fruit;//A
include vars.php;
echo A $color $fruit;//A green Apple
?>
<?php
echo <b>.date(d-m-y).</b>;
?>
<?php
Echo <html><body bgcolor=silver>
Echo welcome to php<br>
Echo Today is:
Include(date.php);
Echo <br>Thank you
Echo </body></html>;
?>
<?php
require prepend.php
require $somefile;
require (somefile.txt);
?>
<center><h2>ODD
Numbers</h2></center>
<hr size=2 />
$num=array(5,14,19,28,31,35,54,63);
echo "<b> Orginal Array:</b><br>";
foreach($num as $n)
echo "$n,";
echo "<br><br>";
<?php
echo "<b>Multiples of 7: </b><br>";
$num=array(5,14,19,28,31,35,54,63);
foreach($num as $n)
if($n%7==0)
echo "$n,";
?>
require("r1.html");
require("r2.php");
require("r3.php");
$_GLOBALS
$_SERVER
an array of server
environment variables
$_GET
$_POST
$_COOKIE
filename.inc )
include_once( filename.inc )
require( filename.inc )
require_once( filename.inc )
<html>
<body>
<form action="get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo
$_GET["email"]; ?>
</body>
</html>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?
><br>
Your email address is: <?php echo
$_POST["email"]; ?>
</body>
</html>
GET METHOD
Information sent from a form with the GET method is visible to
everyone.
GET also has limits on the amount of information to send. The
limitation is about 2000 characters.
The variables are displayed in the URL, it is possible to bookmark
the page.
POST METHOD
Information sent from a form with the POST method is invisible to
others.
It has no limits on the amount of information to send.
The variables are not displayed in the URL, it is not possible to
bookmark the page.
<?php
$myfile = fopen("webdictionary.txt",
"r") or die("Unable to open file!");
echo
fread($myfile,filesize("webdictionary.txt
"));
fclose($myfile);
?>
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
<?php
setcookie("user", "Alex Porter", time()
+3600);
?>
Delete a cookies.
<?php
// set the expiration date to one hour
ago
setcookie("user", "", time()-3600);
?>
Starting a session.
<?php
// start session
session_start();
// register session variables
$_SESSION['name'] = 'Ronald';
$_SESSION['species'] = 'Rabbit';
?>
Parameter
Description
To
Subject
Message
headers
Parameters
<?php
$to="xyz@somdomain.com";
$subject="This is subject";
$message="This is simple text message.";
$header="from:abc@somedomain.com\r\n";
$retval=mail($to,$subject,$message,$header);
if($retval==true)
{
echo "message send successfully...";
}
else
{
echo "Message could not be sent..";
}
?>
<?php
$to="xyz@somedomain.com";
$subject="This is subject";
$message="<b> This is HTML message.</b>";
$message.="<h1>This is headline.</h1>";
$header="From:abc@somedomain.com\r\n";
$header="Cc:afgh@somedomain.com\r\n";
$header.="MIME-Version: 1.0\r\n";
$header.="Content-type: text/html\r\n";
$retval=mail($to,$subject,$message,$header);
if($retval==true)
{
echo "Message sent sucessfully..";
}
else
{
echo "Message could not be sent..";
}
?>
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
Introduction
<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error()); //open
the connection
mysql_select_db("sudhar",$conn); //selet the database is to use
if(mysql_connect)
{
echo successfully connected;
}
mysql_close($conn);//for closing the connection
?>
Syntax
Insert into table name (column name1,
column name2) values
(value1,value2);
<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error()); //open the connection
mysql_select_db("sudhar",$conn); //selet the database is to use
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$empid=$_POST['empid'];
$sql=mysql_query("INSERT INTO emp VALUES('firstname','lastname',empid)"); //execute
the statment
echo $sql;
if(mysql_query($sql,$conn))
{
echo "record inserted!";
}
else
{
echo "something went wrong";
}
?>
Syntax
SELECT column_name(s) FROM
table_name
<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(SELECT * FROM emp);
while($row=mysql_fetch_assoc($query))
{
echo $row[firstname] . .$row[lastname];
echo <br>;
}
?>
Syntax
SELECT column_name(s) FROM
table_name WHERE column_name
operator value
<?php
$conn=mysql_connect("localhost","root","") or
die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(SELECT * FROM emp WHERE
firstname=James);
while($row=mysql_fetch_assoc($query))
{
echo $row[firstname] . .$row[lastname];
echo <br>;
}
?>
Syntax
SELECT column_name(s) FROM
table_name ORDER BY column_name(s)
ASC|DESC
The ORDER BY keyword sorts the records
in ascending order by default.
If you want to sort the records in a
descending order, you can use the DESC
keyword.
<?php
$conn=mysql_connect("localhost","root","") or
die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(SELECT * FROM emp ORDER BY age);
while($row=mysql_fetch_assoc($query))
{
echo $row[firstname] . .$row[lastname];
echo $row[age];
echo <br>;
}
?>
Syntax
UPDATE table_name SET column1=value,
column2=value2,... WHERE
some_column=some_value
<?php
$conn=mysql_connect("localhost","root","")
or die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(UPDATE emp SET
age=25 WHERE firstname=james AND
lastname=miller);
?>
Syntax
DELETE FROM table_name WHERE
some_column = some_value
<?php
$conn=mysql_connect("localhost","root","") or
die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(DELETE FROM emp WHERE
firstname=james);
?>