PHP Notes
PHP Notes
Unit I
Essentials of PHP - Operators and Flow Control - Strings and Arrays.
PHP stands for “Hypertext preprocessor” but it’s also still known its original name Personal
Home Page. It is the server-side programming language that’s taken the web world by strom-php is
far and away the most popular programming language for use on web servers. It was created by
RasmusLerdorf in 1994 ( rasmus wanted a way of logging who was looking at his online resume).
Php got such a good reputation that by 1995 it was available for use by other people.
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the [Link] servers with shorthand support enabled you can start a
scripting block with <? and end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php) rather
than the shorthand form.
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting
code below, we have an example of a simple PHP script which sends the text "Hello World" to the
browser:
<html>
<body>
<?php
echo "Welcome to PHP";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used
to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example
above we have used the echo statement to output the text " Welcome to PHP".
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be
executed.
Comments in PHP
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
Variables in PHP
Variables are used for storing values, like text strings, numbers or [Link] a variable is
declared, it can be used over and over again in your [Link] variables in PHP start with a $ sign
symbol.
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will
not [Link]'s try creating a variable containing a string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
PHP is a Loosely Typed Language. In PHP, a variable does not need to be declared before
adding a value to [Link] the example above, you see that you do not have to tell PHP which data type
the variable [Link] automatically converts the variable to the correct data type, depending on its
value.
In a strongly typed programming language, you have to declare (define) the type and name of
the variable before using [Link] PHP, the variable is declared automatically when you use it.
<?php
$txt="Welcome to php";
echo $txt;
?>
The output of the code above will be:Welcome to php
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
Assignment Operators
Unary operator
Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true
LOGICAL OPERATORS
&& Evaluates to true if both the X>5 && The result is true if condition1(x>5)
condition evaluate to true other Y <5 and condition2 (y<5) are both true. If
wisefalse. one of them false , the result is false.
|| Evaluates to true if at least one X > 5 || The result is true if either
of the conditions evaluates to y <10 condition1(x>5) or condition2 (y<10)
true, and false if none of the or both evaluate to true. If both the
conditions evaluates to true. conditions are false, the result is false
CONDITIONAL OPERATOR
>> Shifts bits to the right, filling sign X=10 >>3 The result of this is 10 divided by
bits at the left and it is also called 23. an explanation is given bellow.
the signed right shift operator
<< Shifts bits to the left filling zeros at X=10<<3 Result of this is 10 multiplied by 23.
the right.
>>> Also called the unsigned shift X= -10 An explanation is given bellow.
operator works like the >> operator, >>> 3
but fills in zeroes for the left.
CONTROL STATEMENTS:
Very often when you write code, you want to perform different actions for different
[Link] can use conditional statements in your code to do [Link] PHP we have the following
conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if a condition is true and another code if
the condition is false
if...elseif....else statement - use this statement to select one of several blocks of code to be executed
switch statement - use this statement to select one of many blocks of code to be executed
Syntax:
if (boolean_expr)
{
statements;
}
else
{
statements;
}
example:
<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
<input type="submit"/>
</form>
</body>
</html>
<?php
if($a%2 ==0)
echo "Given number " , $a ,"is even";
else
echo "Given number " ,$a, "is odd ";
?>
Syntax:
While(Boolean_expr)
{
statements
}
example:
<html>
<body>
<form action="[Link]" method="post">
Enter the value of n <input type ="text" name="n"/><br>
<input type="submit"/>
</form>
</body>
</html>
do ..whileLoop:
In a while loop, the condition is evaluated at the beginning of the loop. If the
condition is false, the body of the loop is not executed. If the body of the loop must be executed at
least once, than thedo..while construct should be used. The do ..while construct places the test
expression at the end of the loop.
The keyword do marks the beginning of the loop. The braces delimit the body of the
loop. Finally, a while statement provides the condition and ends the body of the loop.
Syntax:
do
{
statements;
}while(boolean_expr);
Example program:
<html>
<body>
<form action="[Link]" method="post">
Enter the value of n <input type ="text" name="n"/><br>
<input type="submit"/>
</form>
</body>
</html>
<?php
$f=1;$i=1;
do
{
$f=$f * $i;
$i=$i+1;
}while($i<=$n);
echo $n,” ! value is”, $f;
?>
for Loop:
The while and the do..while loops are used when the number of iterations(the number of the
times the loop body is executed) is not known. The for loop is used in situations when the number of
iterations is known in advance. For example, it can be used to determine the square of each of the
first ten numbers.
The for statement consists of the keyword for, followed by parentheses containing three
expressions each separated by a semicolon. These are the initialization expression, the test
expression and the increment/decrement expression.
Syntax:
for(initialization_expr;test_expr;increment/decrement_expr)
{
statements;
}
6 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
Initialization expression:
The initialization expression is executed only once, when the control is passed to the
loop for the first time. It gives the loop variable an initial value.
Test expression:
The condition is executed each time the control passes to the beginning of the loop.
The body of the loop is executed only after the condition has been checked. If the condition
evaluated to true, the loop is executed otherwise, the control passes to the statement following the
body of the loop.
Increment / Decrement expression:
The increment / decrement expression is always executed when the control returns
to the beginning of the loop.
example:
<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
<input type="submit"/>
</form>
</body>
</html>
<?php
for ( $i=1;$i<=10;$i++)
echo $i,"X",$a,"=",$i * $a,"<br>";
?>
switch statement:
The switch statement is php’s multi way branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As such, it
often provides a better alternative than a large series of if-else-ifstatements .
Syntax:
Switch(expression)
{
casevalue1:
stt.
break;
casevalue2:
Stt.
break;
casevalue n:
Stt.
break;
default: stt.
}
The expression must be of type byte, short, int, or char; each of the values specified in the
case statements must be of a type compatible with the expression. Each case value must be a unique
literal(that is, it must be a constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared with each of
the literal values in the case statements. If a match is found, the code sequence following that case
statement is executed.
<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
Enter the value of b <input type ="text" name="b"/><br>
<input type="submit"/>
</form>
</body>
</html>
<?php
switch($a)
{
case "+":
$g=$b+$c;
echo "add value is",$g;
break;
case "-":
$g=$b-$c;
echo "sub value is",$g;
break;
case "*":
$g=$b*$c;
echo "mul value is",$g;
break;
case "/":
$g=$b/$c;
echo "divide value is",$g;
break;
default:
echo "out of the choice";
}
?>
Conditional operator: ? :
If the condition is true after the ?part will be executed, condition is false after the : part will
be executed.
<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
Enter the value of b <input type ="text" name="b"/><br>
<input type="submit"/>
</form>
</body>
</html> <?php
$c=($a > $b) ?$a : $b;
echo “biggest value is”, $c;
?>
An array is a special variable, which can store multiple values in one single variable.
If you have a list of items (a list of student names, for example), storing the student name in single
variables could look like this:
$std1=”ram”;
$std2=”anbu”;
$std3=”kumar”;
However, what if you want to loop through the student and find a specific one? And what if
you had not 3 students, but 300?The best solution here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by
referring to the array [Link] element in the array has its own index so that it can be easily
[Link], there are three kind of arrays:
Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$std=array("ram","anbu","kumar","rose");
$std[0]=”ram”;
$std[1]=”anbu”;
$std[2]=”kumar”;
$std[3]=”rose”;
Example
In the following example you access the variable values by referring to the array name and index:
<?php
$std[0]=”ram”;
$std[1]=”anbu”;
$std[2]=”kumar”;
$std[3]=”rose”;
echo $std[0] . " and " . $std[1] . " are bright sudents.";
?>
The code above will output:ram and anbu are bright students.
Associative Arrays
An associative array, each ID key is associated with a [Link] storing data about specific
named values, a numerical array is not always the best way to do [Link] associative arrays we can
use the values as keys and assign values to them.
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages[mani]=20;
$ages[pradeep]=21;
$ages[ragu]=22;
<?php
$ages[mani]=20;
$ages[pradeep]=21;
$ages[ragu]=22;
echo” mani is” ,$ages[mani],”years old”;
?> output of the program is: mani is 20 years old
<?php
$ar = array(100,75,150,25);
for ($i=0; $i<= 4; $i++) //prints the array elements
echo $ar[$i]."<br \>";
sort($ar);
echo " sorted values are";
for ($i=0; $i<= 4; $i++)
{
echo $ar[$i]."<br \>";
}
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.
String functions:
[Link].
<html>
<body>
<font size ="6">
<?php
$x=array($a,$b,$c,$d,$e,$f);
for($i=0;$i<=5;$i++)
{
echo "given ",$i,"string is:",$x[$i],"<br>";
}
echo "concatnation of first & second string is:",$a.$b,"<br>";
echo "string length of the given 3rd string is:", strlen($c),"<br>";
echo "upper case functon of 4th string: ",strtoupper ($d),"<br>";
echo "lower case functon of 5th : ",strtolower ($e),"<br>";
echo "string reverse function of 6th string is: ", strrev($f),"<br>";
echo "string comparision first & second :",strcmp($a,$b),"<br>";
echo "string replace functin given string is php lab output is project lab:",
str_replace("php","lab","projectphp")."<BR>";
echo "string possiton function: given string is bcaphp lab, php :",
strpos("bcaphp lab!","php","<br>");
$f=strrev($a);
if(strcmp($a,$f)==0)
echo "given string is polyndrome";
else
echo "given string is not polyndrome";
?>
</font>
</html>
I unit over
FUNCTIONS:
It is a sub program. It will be reduce the size of the program by calling and using them at
different places in the program.
The advantages are: Re-usability, modularity, overall programming simplicity.
Function function_name([argument_list …] )
{ statements;
return ([return value] );
}
Example:
<?php
display();
function display()
{
echo "welcome to php function program";
}
?>
Passing functions some data:
In this method php program to call the function with argument that value passing to that
particular function then only it will be executed.
<?
echo "function with argument";
sqr(4);
functionsqr($a)
{
$b=$a * $a;
echo "square of ", $a, " is : ", $b;
}
?>
<?php
echo "return type of function : ",sqr($a);
functionsqr($a)
{
$b=$a * $a;
return $b;
}
?>
Nested function:
A function within another one function is called nested [Link] functions will not
exist before their parent function has been called. Knowing this, you should be able to avoid some
common developer mistakes.
Once you have called the parent function, the child function will become accessible
anywhere in the script.
<?
sqr($a);
sqr1();
functionsqr($a)
{
echo "welcome to nested function <br>";
function sqr1()
{
echo "welcome to inner function <br>";
}
$b=$a * $a;
echo "square value of : ", $b, "<br>";
}
?>
The NAME of our textbox is username. It's this name that we will be using in a PHP scrip
<html>
<body>
<form action="[Link]" method ="get">
What's your name ?<input type ="text" name="data"><br>
<input type ="submit" value ="send">
<input type ="reset" value ="reset">
</form>
</body>
</html>
Text area:
<html>
<body>
<form action="[Link]" method ="post">
Enter the data into text areas
</form>
</body>
</html>
<?PHP
$text =$_REQUEST["data"];
echostr_replace("\n","<br>",$text);
Check boxes:
<html>
<body>
<form action="[Link]" method ="post">
Enter your course detail:
List boxes:
<html>
<body>
<form action="[Link]" method ="post">
select your ice cream flavors:
</form>
</body>
</html>
<?PHP
echo $_REQUEST["icecream"];
?>
Password control:
<html>
<body>
<form action="[Link]" method ="post">
Enter your password :
<input type ="password" name="password">
<input type ="submit" value ="send">
</form>
</body>
</html>
<?PHP
if($_REQUEST["password"]=="arun")
{
echo " your password is correct","<br>";
echo " this is password control prgram";
}
?>
Image control:
<html>
<body>
).
<html>
<body>
<?php
$handle=fopen($_FILES['userfile']['tmp_name'],"r");
while(!feof($handle))
{
$text=fgets($handle);
echo $text,"<br>";
}
fclose($handle);
?>
Button control:
<html>
<body>
<form action="[Link]" method ="post">
enter the a value <input type="text" name="a"/><br>
enter the b <input type="text" name="b"/><br>
<input type ="submit" value ="add" name = "button">
<input type ="submit" value ="sub" name = "button">
<input type ="submit" value ="mul" name = "button">
$x=$_REQUEST["button"];
if($x=="add")
{
echo "you click button 1";
$c=$a+$b;
echo " add value is",$c;
}
elseif($x=="sub")
{
echo "you click button 2";
$c=$a-$b;
echo " sub value is",$c;
}
else
{
echo "you click button3";
$c=$a*$b;
echo " mul value is",$c;
}
?>
Syntax
function functionName()
{
code to be executed;
}
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
FUNCTION
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
echo $total;
}
add(1,16);
?>
</body>
</html>
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " , add(1,16);
?>
class
Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of
curly braces which enclose the definitions of the properties and methods belonging to the class.
The class name can be any valid label which is a not a PHP reserved word. A valid class name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores
Class program:
<?php
class one
{
function show()
{
echo "welcome to php class";
}
}
$a=new one();
$a->show();
?>
Constructor
To allocate a memory.
PHP 5 allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
24 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
<?php
class one
{
var $a,$b,$c,$d,$e;
function __construct($x,$y)
{
$this->a=$x;
$this->b=$y;
}
function show()
{
echo "a value is",$this->a,"<br>";
echo "b value is",$this->b,"<br>";
$this->c=$this->a + $this->b;
echo "add value is",$this->c,"<br>";
}
}
echo "example of constructor<br>";
$t=new one(4,6);
$t->show();
Destructor
A destructor, as the name implies, is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose name is the same as the
class name.
A destructor never takes any argument nor does it return any value. It will be invoked
implicitly be the compiler upon exit from the program to clean up storage that is no longer
accessible. It is good practice to declare destructors in a program since it releases memory space for
future use.
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as
C++. The destructor method will be called as soon as all references to a particular object are
removed or when the object is explicitly destroyed or in any order in shutdown sequence.
<?php
class one
{
var $a,$b,$c,$d,$e; R. Arun kumar Head, Dept of C.A , SCAS,
PBLR
function __construct($x,$y)
Inheritance:
Inheritance is new class derived from old class. Some modification about particular class. It
should invoke super class(base class) & sub class(derived class).
Types of inheritance:
1. Single Inheritance (only one super class).
2. multiple inheritance (several super class).
3. Multilevel inheritance (derived from a derived class).
4. Hybrid Inheritance (combination of multiple and multilevel inheritance).
5. Hierarchical inheritance ( one super class, many subclasses).
Defining a subclass:
class subclass name extends super class name
{
variable declaration;
function declaration;
The keyword extends signifies that the properties of the super class name are extended to the
subclass name. The subclass will now contain its own variables and methods as well those of the
super class. This kind of situation occurs when we want to add some more properties to an existing
class without actually modifying it.
Multilevel inheritance:
<?php
class one
{
var $a,$b,$c,$d,$e;
function cal($x,$y) R. Arun kumar Head, Dept of C.A , SCAS, PBLR
{
$this->a=$x;
We will briefly build an HTML form, and call the form data using PHP. PHP offers several
methods for achieving this goal, so feel free to substitute alternative methods as you follow along.
Our example will show you a method using a single .php file, combining both PHP and HTML in
one simple text file,
Input Fields:
As mentioned in the Forms Tutorial, just be sure to place the name attribute within the tags and
specify a name for the field. Also be aware that for our form's action we have placed the
$PHP_SELF super global to send our form to itself.
Text area:
In reality, textareas are oversized input fields. Treat them the same way, just be aware of
the wrap attribute and how each type of wrap will turn out. PHP relys on this attribute to display the
textarea
The catch with radio buttons lies with the value attribute. The text you place under the value
attribute will be displayed by the browser when the variable is called with PHP.
Check boxes require the use of an array. PHP will automatically place the checked boxes into
an array if you place [] brackets at the end of each name.
Selection List:
To name a selection form, place the name attribute within the select tags at the beginning of the
form, and then place the appropriate value to fit each option.
Submission button:
We mentioned that the submission button was missing. Now's the time to throw it into the
existing code. The button is the same as any submission button, the only thing we need to be sure to
add is a name to it so we can call it later using PHP.
Example:
</head>
<body>
<form method="post" action="[Link]">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
Gender:<br />
Male:<input type="radio" value="Male" name="gender"><br />
Female:<input type="radio" value="Female" name="gender"><br />
[Link]
<font size=6>
<?php
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
echo $quote,"<br>";
echo "your education is :", $education,"<br>";
echo "your favirote time is: ", $TofD,"<br>";
?>
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
<?php
setcookie("user", "Alex Porter", time()+3600);
echo "cookie is set now";
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
<a href="[Link]">[Link]</a>
</html>
PHP Sessions
A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?> R. Arun kumar Head, Dept of C.A , SCAS,
PBLR
Destroying a Session
You can also completely destroy the session by calling the session_destroy() function:
Note: session_destroy() will reset your session and you will lose all your stored session data.
<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password to access this resource\n";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER']))
{
authenticate();
} else
{
echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']);
echo "<form action='' method='post'>\n";
echo "<input type='hidden' name='SeenBefore' value='1' />\n";
echo "<input type='hidden' name='OldAuth' value=\"" .
htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "\" />\n";
echo "<input type='submit' value='Re Authenticate' />\n";
echo "</form></p>\n";
} ?>
Another example:
<?php
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; ?>
It will give current username and password.
The enctype attribute of the <form> tag specifies which content-type to use when submitting
the form. "multipart/form-data" is used when a form requires binary data, like the contents of
a file, to be uploaded
The type="file" attribute of the <input> tag specifies that the input should be processed as a
file. For example, when viewed in a browser, there will be a browse-button next to the input
field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file
uploads.
By using the global PHP $_FILES array you can upload files from a client computer to the remote
server.
The first parameter is the form's input name and the second index can be either "name", "type",
"size", "tmp_name" or "error". Like this:
This is a very simple way of uploading files. For security reasons, you should add restrictions on
what the user is allowed to upload.
File upload:
<html>
<body>
<?php
echo " this is the content of the file","<br>";
$file=fopen($_FILES["file"]["tmp_name"],"r");
while(!feof($file))
{
$text=fgets($file);
echo $text,"<br>";
}
fclose($file);
Another example:
33 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
<?php
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"],"<br>";
echo " this is the content of the file","<br>";
$file=fopen($_FILES["file"]["tmp_name"],"r");
while(!feof($file))
{
$text=fgets($file);
echo $text,"<br>";
}
fclose($file);?>
database:
mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
username Optional. Specifies the username to log in with. Default value is the name of the
user that owns the server process
Closing a Connection
The connection will be closed automatically when the script ends. To close the connection before,
use the mysql_close() function:
A database holds one or multiple tables.
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
Create a Table
34 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
The CREATE TABLE statement is used to create a table in MySQL.
Syntax
We must add the CREATE TABLE statement to the mysql_query() function to execute the
command.
Important: A database must be selected before a table can be created. The database is selected with
the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the maximum length of
the field, e.g. varchar(15).
The INSERT INTO statement is used to add new records to a database table.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
To get PHP to execute the statements above we must use the mysql_query() function. This function
is used to send a query or command to a MySQL connection.
Select Data From a Database Table
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
<?php
$con=mysql_connect("localhost","root","vertrigo");
$db=mysql_select_db("arun",$con);
$query="update mca1 set name='arun' where name='kumar'";
$result=mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>name</th><th>gender</th>";
$query="select * from mca1";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>",$row['name'],"</td><td>",$row['rno'];
echo "</tr>";
}
echo"</table>";
mysql_close($con);
?>
R. Arun kumar Head, Dept of C.A , SCAS,
PBLR
The DELETE FROM statement is used to delete records from a database table.
Syntax
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record
or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
<?php
$con=mysql_connect("localhost","root","vertrigo");
$db=mysql_select_db("arun",$con);
FTP Functions
Function Description
ftp_alloc() Allocates space for a file to be uploaded to the FTP server
ftp_cdup() Changes to the parent directory on the FTP server
ftp_chdir() Changes the current directory on the FTP server
ftp_chmod() Sets permissions on a file via FTP
ftp_close() Closes an FTP connection
ftp_connect() Opens an FTP connection
ftp_delete() Deletes a file on the FTP server
ftp_exec() Executes a command on the FTP server
Downloads a file from the FTP server and saves it into an open local
ftp_fget()
file
ftp_fput() Uploads from an open file and saves it to a file on the FTP server
ftp_get_option() Returns runtime options of the FTP connection
ftp_get() Downloads a file from the FTP server
ftp_login() Logs in to the FTP connection
ftp_mdtm() Returns the last modified time of a specified file
ftp_mkdir() Creates a new directory on the FTP server
ftp_nb_continue() Continues retrieving/sending a file (non-blocking)
Downloads a file from the FTP server and saves it into an open file
ftp_nb_fget()
(non-blocking)
Uploads from an open file and saves it to a file on the FTP server
ftp_nb_fput()
(non-blocking)
ftp_nb_get() Downloads a file from the FTP server (non-blocking)
ftp_nb_put() Uploads a file to the FTP server (non-blocking)
ftp_nlist() Returns a list of files in the specified directory on the FTP server
ftp_pasv() Turns passive mode on or off
ftp_put() Uploads a file to the FTP server
ftp_pwd() Returns the current directory name
ftp_quit() An alias of ftp_close()
ftp_raw() Sends a raw command to the FTP server
ftp_rawlist() Returns a list of files with file information from a specified directory
ftp_rename() Renames a file or directory on the FTP server
ftp_rmdir() Deletes an empty directory on the FTP server
ftp_set_option() Sets runtime options for the FTP connection
ftp_site() Sends an FTP SITE command to the FTP server
ftp_size() Returns the size of the specified file
ftp_ssl_connect() Opens a secure SSL-FTP connection
ftp_systype() Returns the system type identifier of the FTP server
FTP_put():(upload file)
Syntax:
ftp_put(ftp_connection,remote_file,local_file,mode,startpos);
Example:
if(ftp_get($ftp_con,$local_file,$server_file,FTP_ASCII))
{
echo $file;
}
else
{
echo $file;
}
ftp_close($ftp_conn);
Example
<?php
// connect and login to FTP server
$ftp_server = "[Link]";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
// upload file
if (ftp_fput($ftp_conn, "[Link]", $fp, FTP_ASCII))
{
echo "Successfully uploaded $file.";
}
else
{
echo "Error uploading $file.";
}
Parameter Description
ftp_connection Required. Specifies the FTP connection to use
remote_file Required. Specifies the file path to upload to
open_file Required. Specifies an open local file. Reading stops at end of file
Required. Specifies the transfer mode. Possible values: FTP_ASCII or
mode
FTP_BINARY
startpos Optional. Specifies the position in the remote file to start uploading to
Example
<?php
// connect and login to FTP server
$ftp_server = "[Link]";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
// then do something...
// close connection
ftp_close($ftp_conn);
?>
Syntax
ftp_close(ftp_connection);
Parameter Description
ftp_connection Required. Specifies the FTP connection to close
Example
<?php
// connect to FTP server
$ftp_server = "[Link]";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
// login
if (@ftp_login($ftp_conn, $ftp_username, $ftp_userpass))
{
echo "Connection established.";
}
else
{
echo "Couldn't establish a connection.";
}
// close connection
ftp_close($ftp_conn);
?>
Syntax
ftp_login(ftp_connection,username,password);
Parameter Description
ftp_connection Required. Specifies the FTP connection to use
username Required. Specifies the username to login with
password Required. Specifies the password to login with