PHP - 5 - Units Notes - PPT
PHP - 5 - Units Notes - PPT
Sathish, CSE
Branch : ECE
Subject Name : PHP Programming
Chapter - 1
Introduction to
PHP
1.Introduction to PHP
This unit covers…
source
1.2 Relationship between Apache, MySQL and PHP
(AMP module)
1.3 PHP configurations in PHP
1.4 Apache web server
Inside Httpd.conf
• Traditionaly httpd.conf contained general settings such as
the ServerName and Port number. These entries appear
as follows in the file:
ServerName localhost
Port 80
Basics of PHP
2.Basics of PHP
This unit covers…
2.1 PHP Structure and syntax
2.2 Creating the PHP pages
2.3 Rules for PHP syntax
2.4 Integrating HTML with PHP
2.5 Constants, Variable: static and global variable
2.6 Conditional structure and looping
2.7 PHP operator
2.8 Arrays foreach construct
2.9 User defined function, argument function, variable
function, return function, default argument, variable
length argument
Developed By: Amit Lakhani, TFGP Adipur
2.1
PHP structure and
syntax
<html>
<head>
<title>PHP Test</title>
</head> PHP statement
<body>
<?php echo ‘<p>Hello World!</p>’; ?>
</body>
</html>
// This is a comment
# This is also a comment
/* This is a comment
that is spread over
multiple lines */
<?php
echo ‘Claire O\’Reilly ’;
echo “said \”Hello\”.”;
?>
Developed By: Amit Lakhani, TFGP Adipur
Variables: What are they?
When we work in PHP, we often need a labelled place to
store a value (be it a string, number, whatever) so we can
use it in multiple places in our script.
These labelled ‘places’ are called VARIABLES
Variable naming Rules:
• $ followed by variable name
• Case sensitive
• $variable differs from $Variable
• Stick to lower-case to be sure!
• Name must started with a letter or an underscore
• Followed by any number of letters, numbers
and underscores
<?php
$name = ‘Phil’;
$age = 23;
echo $name;
echo ’ is ‘;
echo $age;
// Phil is 23
?>
<html>
<head>
<title>PHP Test</title>
</head> PHP statement
<body>
<?php echo ‘<p>Hello World!</p>’; ?>
</body>
</html>
<?php
define(‘NAME’,‘Phil’);
define(‘AGE’,23);
echo NAME;
echo ’ is ‘;
echo AGE;
// Phil is 23
?> Developed By: Amit Lakhani, TFGP Adipur
2.6
Conditional
Structure and
Looping
Developed By: Amit Lakhani, TFGP Adipur
Control Structures
• To do something depending on a
comparison, use an if statement.
if (comparison) {
expressions; // do if TRUE
}
• NB: Notice the curly brackets – these are
important!
<?php
$a = 10;
$b = 13;
if ($a<$b)
{
echo ‘a is smaller than b’;
}
?>
$a = 10;
$b = 13;
if ($a<$b) {
echo ‘a is smaller than b’;
} elseif ($a==$b) {
echo ‘a is equal to b’;
} else {
echo ‘a is bigger than b’;
}
while (comparison)
{
expressions;
}
$i = 1;
while ($i <= 10)
{
echo $i++;
}
An alternative...
$i = 1;
do {
echo $i++;
}
while ($i <= 10);
$letters = array(‘a’,’b’,’c’);
foreach ($letters as $value)
{
echo $value;
} // outputs a,b,c in turn
$letters = array(‘a’,’b’,’c’);
foreach ($letters as $key => $value)
{
echo “array $key to $value”;
}
<?php
$name = ‘Rob’;
echo $name;
?>
e.g.
$firstname = ‘Rob’;
$surname = ‘Tuley’;
// displays ‘Rob Tuley’
echo $firstname.’ ‘.$surname;
Example Result
$a .= $b Equivalent to $a = $a.$b.
$a = 4;
$b = 2;
$c = $a + $b + ($a/$b);
// $c has value 4+2+(4/2) = 8
print_r($letters);
$surname[‘rob’] = ‘Tuley’;
$surname[‘si’] = ‘Lewis’;
<?php
$dept['comp'] = "32";
$dept['it'] = "30";
$dept['ec'] = "34";
print_r($dept['it']);
?>
Output:
<?php
$varArray=array(1,2,3,4,5);
$varArray_1=array(6,7,8,9);
print_r($arr_merge);
Combines
?> Elements of array
Output:
<?php
$varArray['one']= "second";
$varArray['two']= "first";
$varArray['three']= "third";
asort($varArray); Sort an array
print_r($varArray);
?> Developed By: Amit Lakhani, TFGP Adipur
Sorting arrays conti..
• Sorting an Array by Its Keys using ksort():
Particularly with regard to associative arrays, it is just
as important to be able to sort arrays by their keys as it is
by their values. The ksort() function accomplishes this
while maintaining the relationship between keys and
values.
<?php
$varArray['one']= "second";
$varArray['two']= "first";
$varArray['three']= "third";
ksort($varArray); Sort an array
By its keys
print_r($varArray);
?>
Developed By: Amit Lakhani, TFGP Adipur
Sorting arrays conti..
• Reversing an Array Using arsort():
To sort an associative array by value in reverse order,
use arsort(). Like asort(), this function preserves the
array’s keys.
<?php
$varArray_1['one']= "second";
$varArray_1['two']= "first";
$varArray_1['three']= "third";
arsort($varArray_1); Sort an array
In reverse order
print_r($varArray_1);
?>
<?php
$varArray_1['one']= "second";
$varArray_1['two']= "first";
$varArray_1['three']= "third";
krsort($varArray_1); Sort an array
In reverse order
print_r($varArray_1);
?>
<?php
$varArray_1['one']= "second";
$varArray_1['two']= "first";
$varArray_1['three']= "third";
array_reverse($varArray_1);
print_r($varArray_1);
?> Sort an array
In reverse order
Developed By: Amit Lakhani, TFGP Adipur
Sorting arrays example
<?php
$varArray= array(1,2,3,4,5);
print_r($varArray);
foreach($varArray as $val)
{
print_r("$val");
echo"<br>";
}
?>
Developed By: Amit Lakhani, TFGP Adipur
Array operators
Example Name Result
$a + $b Union Union of $a and $b.
$a==$b Equality TRUE if $a and $b have the
same key/value pairs
$a===$b Identity TRUE if $a and $b have the
same key/value pairs in the
same order of the same type.
$a!=$b Inequality TRUE if $a is not equal to $b
$a<>$b Inequality TRUE if $a is not equal to $b
$a!==$b Non-identity TRUE if $a is not identical to $b
• Argument functions
• Variable functions
• Return functions
• Default argument
function display($name)
{
foreach(func_get_args() as $arg)
{
echo $arg."<br>";
} Output:
display("computer","IT","EC");
?>
Department
parent
children
Computer Mechanical
class sample
{
var $count;
}
class sample
{
private $count;
}
Developed By: Amit Lakhani, TFGP Adipur
Access specifier conti…
• Protected member:
• A protected property or method is accessible in the
class in which it is declared, as well as in classes that
extends that class.
• Protected members are not available outside of those
two classes.
• A class member can be made protected using
protected keyword in front of the member.
class sample
{
protected $count;
}
Developed By: Amit Lakhani, TFGP Adipur
Interface
• Example:
<?php
$var=21; Output:
echo gettype($var);
?>
Developed By: Amit Lakhani, TFGP Adipur
settype() function
• determine if a variable is set and is not NULL
• Example:
<?php
$var=21; Output:
settype($var, "string");
echo gettype($var);
?>
Developed By: Amit Lakhani, TFGP Adipur
isset() function
• set the type of variable
• Syntax: bool isset($var, “type”)
• Returns TRUE on success otherwise false
<?php
$var=NULL;
if (isset($var)=="TRUE")
{ Output:
echo "var is set";
}
else
{
echo "var is not set";
}echo gettype($var);?>
Developed By: Amit Lakhani, TFGP Adipur
unset() function
• unset a given variable
• Example:
<?php
$var="comp";
echo "before unset<br>" .$var;
echo gettype($var);
unset($var);
echo "after unset<br>".$var;
echo gettype($var);
?>
Developed By: Amit Lakhani, TFGP Adipur
strval() function
•Get string value of a variable
Example:
<?php
$var=25;
echo strval($var);
?>
Output:
Example:
<?php
$var=25;
echo floatval($var);
?>
Output:
Example:
<?php Output:
echo intval(42);
echo "<br>";
echo intval(4.2);
?>
•Example:
<?php
$var=array(1,2,3,4,5);
echo print_r($var);
?>
Output:
Example:
<?php
Output:
$var=1;
$var2=40.50;
echo var_dump($var);
echo"<br>";
echo var_dump($var2);
?> Developed By: Amit Lakhani, TFGP Adipur
3.2
String functions
• Example:
<?php
echo "The character value of of 52 is: ".chr(52);
?>
Output:
• Example:
<?php
echo ord("computer");
?>
Output:
• Example:
<?php
echo "The output of string lower function:<br>";
echo strtolower("Computer DEPT.");
?>
Output:
• Example:
<?php
echo "The output of string upper function:<br>";
echo strtoupper("Computer DEPT.");
?>
Output:
• Example:
<?php
echo "The output of string length function:<br>";
echo strlen("Computer");
?>
Output:
• Syntax: rtrim($str)
<?php
echo "The output of rtrim function:<br>";
$str = "Computer department ";
echo "Without rtrim: " . $str;
echo "The length of the string is:". strlen($str);
echo "With rtrim: " . $str;
echo "The length of the string is:". Strlen(rtrim($str));
?>
• Example:
<?php
echo "The output of substring function:<br>";
echo substr("Computer department!",3);
echo substr("Computer department!",3,5);
?>
Output:
•Example:
<?php
echo "The output of string position function:<br>";
echo strpos("Computer","m“, 2);
?>
Output:
•Example:
<?php
echo "The output of string position function:<br>";
echo strrpos("Computer","m“, 2);
?>
Output:
The output of string position function:
2
• Syntax: strstr($str,search)
•Example:
<?php
echo "The output of strstr() function:<br>";
echo strstr("Computer","m“);
?>
Output:
• Syntax: stristr($str,search)
•Example:
<?php
echo "The output of stristr() function:<br>";
echo stristr("Computer","m“);
?>
•Example:
<?php
echo "The output of string replace function with case
sensitive: <br>";
echo str_replace("department","engg.","computer
department", $i);
echo $i;
?>
Developed By: Amit Lakhani, TFGP Adipur
strrev() function
• reverse a string
•Example:
<?php
echo "The output of strrev() function: <br>";
echo strrev("computer department”);
?>
Output:
•Example:
<?php
echo "The output of echo function<br>";
$i=1;
echo $i;
?>
•Example:
<?php
print (“The output of print function<br>“);
$i=1;
print $i;
?>
•Syntax: abs(num)
• Example:
<?php
echo "The output of abs() function<br>";
echo(abs(6.99) . "<br />");
echo(abs(-3) . "<br />");
echo(abs(3));
?>
Developed By: Amit Lakhani, TFGP Adipur
ceil() function
• returns the value of a number rounded UPWARDS to the
nearest integer.
• Syntax: float ceil(num)
• Example:
<?php
echo "The output of ceil() function<br>";
echo(ceil(0.60) . "<br />");
echo(ceil(0.40) . "<br />");
echo(ceil(5) . "<br />");
echo(ceil(5.1) . "<br />");
?>
Developed By: Amit Lakhani, TFGP Adipur
floor() function
• returns the next lowest integer value by rounding down
value.
• Syntax: float floor(num)
• Example:
<?php
echo "The output of floor() function<br>";
echo(floor(0.60) . "<br />");
echo(floor(0.40) . "<br />");
echo(floor(5.1) . "<br />");
echo(floor(-5.1) . "<br />");
?>
Developed By: Amit Lakhani, TFGP Adipur
round() function
• returns the rounded value to specified precision.
• Example:
<?php
echo "The output of round() function<br>";
echo(round(0.60) . "<br />");
echo(round(10.28765,2) . "<br />");
echo(round(-4.40) . "<br />");
echo(round(-4.60));
?>
Developed By: Amit Lakhani, TFGP Adipur
fmod() function
• returns the floating point remainder of dividing the
dividend by the divisor.
• Example:
<?php
echo "The output of fmod() function to
display remainder(modulo)<br>";
$r = fmod(5,2);
echo $r;
?>
Developed By: Amit Lakhani, TFGP Adipur
min() function
• returns smallest value
• Example:
<?php
echo "The output of min() function <br>";
$r = min(5,2);
echo $r;
?>
• Example:
<?php
echo "The output of max() function <br>";
echo(max(5,7) . "<br />");
echo(max(-3,5) . "<br />");
?>
• Example:
<?php
echo "The output of pow() function <br>";
echo pow(4,2) . "<br />";
echo pow(6,2) . "<br />";
?>
• Example:
<?php
echo "The output of sqrt() function <br>";
echo(sqrt(1) . "<br />");
echo(sqrt(9) . "<br />");
?>
• Example:
<?php
echo "The output of rand() function <br>";
echo(rand() . "<br />");
echo(rand(10,100));
?>
• Example:
<?php
echo "The output of date() function”;
echo date("d");
echo date("D");
echo date("j");
?>
Developed By: Amit Lakhani, TFGP Adipur
date() function formats
Required. Specifies how to return the result:
d - The day of the month (from 01 to 31)
D - A textual representation of a day (three letters)
j - The day of the month without leading zeros (1 to 31)
l (lowercase 'L') - A full textual representation of a day
N - The ISO-8601 numeric representation of a day (1 for
Monday through 7 for Sunday)
S - The English ordinal suffix for the day of the month (2
characters st, nd, rd or th. Works well with j)
w - A numeric representation of the day (0 for Sunday
through 6 for Saturday)
z - The day of the year (from 0 through 365)
W - The ISO-8601 week number of year (weeks starting
on Monday)
December)
m - A numeric representation of a month (from 01 to 12)
M - A short textual representation of a month (three letters)
n - A numeric representation of a month, without leading
zeros (1 to 12)
t - The number of days in the given month
L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
o - The ISO-8601 year number
Y - A four digit representation of a year
y - A two digit representation of a year
• Example:
<?php
echo "The output of getdate() function<br>";
print_r(getdate());
?>
• Example:
<?php
echo "The output of setdate() function<br>";
$d=new DateTime();
$d->setDate(2011,4,2);
echo $d->format('d-m-y');
?>
Developed By: Amit Lakhani, TFGP Adipur
checkdate() function
• Checks the validity of the date formed by the argument
• Example:
<?php
echo "The output of checkdate() function<br>";
print_r(checkdate(11,30,2000));
?>
Developed By: Amit Lakhani, TFGP Adipur
time() function
• Returns the current UNIX timestamp
• Example:
<?php
echo "The output of time() function<br>";
echo time();
?>
Developed By: Amit Lakhani, TFGP Adipur
mktime() function
• Returns the UNIX timestamp corresponding to the
arguments given.
•Example:
<?php
echo "The output of mktime() function<br>";
echo mktime();
echo(date("M-d-Y",mktime(0,0,0,12,36,2001)));
echo(date("M-d-Y",mktime(0,0,0,14,1,2001)));
?> Developed By: Amit Lakhani, TFGP Adipur
3.5
Array functions
• Syntax: count($var)
• Example:
<?php
$varArray=array(1,2,3,4,5);
echo "The number of elements in first
array=".count($varArray);
?>
Output:
• Example:
<?php
echo "The output of array_count_values() function<br>";
$arr=array(1,2,3,4,5);
print_r(array_count_values($arr));
?>
Output:
Example:
<?php
echo "The output of list() function<br>";
$arr=array(1,2,3);
list($a,$b,$c)=$arr;
echo “The list of values are:<br> $a <br> $b <br> $c ";
?>
Developed By: Amit Lakhani, TFGP Adipur
In_array() function
• checks if a value exists in an array
• Example:
<?php
$varArray=array(1,2,3);
if(in_array(1,$varArray))
{
print_r($varArray[1]);
}
?>
• Example:
<?php
$arr=array(1,2,3);
echo "The current element is ". current($arr);
?>
Output:
• Example:
<?php
$arr=array(1,2,3);
echo "The current element is ". current($arr);
echo "<br>The next element is ". next($arr);
?>
Output:
• Example:
<?php
$arr=array(1,2,3);
echo "The current element is ". current($arr);
echo "<br>The next element is ". next($arr);
echo "<br>The next element is ". prev($arr);
?> Output:
• Example:
<?php
$arr=array(1,2,3);
echo "The last element is ". end($arr);
?>
Output:
• Example:
<?php
$arr=array(1,2,3);
$ele=each($arr);
echo "The element is ";
print_r($ele);
?>
• Example:
<?php
$arr=array(1,2,3);
sort($arr);
print_r($arr);
?>
Output:
• Example:
<?php
$arr=array(1,2,3);
$arr_1=array(4,5,6);
$arr_2=array_merge($arr, $arr_1);
print_r($arr_2);
?>
Developed By: Amit Lakhani, TFGP Adipur
Array_reverse() function
• Returns the array with the order of the elements
reversed.
• Example:
<?php
$arr=array(1,2,3);
$arr_2=array_reverse($arr);
print_r($arr_2);
?>
Output:
• Example:
<?php
$arr=array(1,2,3);
$arr_2=array_sum($arr);
print_r($arr_2);
?>
Output:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"computer department");
fclose($file);
?>
• Syntax: fread(file,length)
• Example:
<?php
$file = fopen("test.txt","r");
echo fread($file,5);
fclose($file);
?>
• Example:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"computer department");
fclose($file);
?>
• Syntax: fclose($filename)
• Example:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"computer department");
fclose($file);
?>
• Textboxes
• Password boxes
• Check boxes
• Option buttons
• Submit
• Reset
• File
• Hidden
• Image
Textbox
password
Text area
checkbox
<html>
<form>
Radio button element
<font size=5>
Select Your Gender:
<input type= "radio" name="rdgender"
value="male">Male<br>
<input type= "radio" name="rdgender"
value="female">Female<br></form>
</html>
Radio buttons
Attributes:
•Name:- variable name to be sent to the application.
• Size:- sets the number of visible choices.
• Multiple:- presense of this attribute allow the user to
make multiple selection
Developed By: Amit Lakhani, TFGP Adipur
Option Input
List items are added to the <OPTION> </OPTION>
Element.
<OPTION> </OPTION>
Attributes:
• Selected:- When this attribute presents, the option is
selected when the document is initially
loaded.
• Value:- Specifies the value the variable named in the
select element.
<html>
<form>
Select Your Gender:<br>
<select name="lang">
<option > English</option>
<option selected> Hindi</option>
<option> Gujarati</option>
</select>
</html>
Select with option element
Developed By: Amit Lakhani, TFGP Adipur
Output of select example with dropdown menu
Selected value
<html>
<form>
Select Your Language:<br>
<select name="lang" size=3 multiple="true">
<option > English</option>
<option selected > Hindi</option>
<option> Gujarati</option>
</select>
</html>
Select with option element
Developed By: Amit Lakhani, TFGP Adipur
Output of select example with list box
<html>
<form>
First Name:
<input type= "text" name="txtfname">
Last Name:
<input type= "text" name="txtlname" >
<input type= “button" name="btnsubmit" value =
"Send">
</form>
</html> Push button input
button
<html>
<form>
First Name:
<input type= "text" name="txtfname">
Last Name:
<input type= "text" name="txtlname" >
<input type= “submit" name="btnsubmit" value =
"Send">
</form>
</html> submit button input
Submit button
• Type:- image
• Name:- Specifies the name to be used in scripting.
• SRC:- URL of the image file.
<html>
<form>
First Name:
<input type= "text" name="txtfname">
Last Name:
<input type= "text" name="txtlname" >
<input type= “image“ src=”…” name="btnsubmit"
value = "Send">
</form>
</html> submit button input
image button
<INPUT TYPE=“RESET”>
Attributes:
• Type:- reset
• Value:- determine the text label on the button.
<html>
<form>
First Name:
<input type= "text" name="txtfname">
Last Name:
<input type= "text" name="txtlname" >
<input type= "submit">
<input type= "reset">
</form>
</html> reset button input
reset button
• When you create a form you have two choices for the
METHOD attribute. You can use one of the following two
methods to pass information between pages.
• GET method
• POST method
• They both pass the data entered into the form along with
the form field name to the web server.
Developed By: Amit Lakhani, TFGP Adipur
Processing the form
• GET method
When GET method is used in the METHOD attribute
of FORM element, the value entered in the input
elements are displayed in URL.
Output
Output of
of post
post method
method
When “Send”
button is clicked,
value in the text
box is sent to the
get.php and are
displayed in
browser
Output of get.php
When “Send”
button is clicked,
value in the text
box is sent to the
post.php and are
displayed in
browser
Output of post.php
checkbox
<html>
<form>
Radio button element
<font size=5>
Select Your Gender:
<input type= "radio" name="rdgender"
value="male">Male<br>
<input type= "radio" name="rdgender"
value="female">Female<br></form>
</html>
Radio buttons
• The submit button can share the same name but supply
different values.
<?php
if ($_POST['display']=="Show Name")
{
echo "Your name is:" .$_POST['fname'];
}
Here, we just check for the value submitted for the
else Submit button
{
echo " Your Address is:" .$_POST['address'];
}
?>
Developed By: Amit Lakhani, TFGP Adipur
Output of form with multiple submit
Output of form_multiple_submit.php
Depending on
the button you
click and the data
you choose
To enter , this
code outputs
different
Output of multiple_submit_post.php information.
Check whether a
string contains
only digits, if the
digits are entered
in name, it warns
user to enter only
alphabet in name
Output of validation_post.php
Dynamic_title_header.php
<title>
<?php
if (isset($title))
print $title;
Else
print "default title";
?></title> Developed By: Amit Lakhani, TFGP Adipur
4.3.7
Manipulating the string
as an array
$string=“computer”;
$string=array(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’);
• This states that we can use string as an array and we can
manipulate string as an array using functions.
• Example:
<?php
Print_r(str_split(“computer”));
?>
Splits the string
Output:
• Example:
<?php
$str="Hi, This is computer department";
print_r(explode(",",$str));
print_r(explode(" ",$str)); breaks the string
print_r(explode(" ",$str,3));
?>
Developed By: Amit Lakhani, TFGP Adipur
Output of explode() function
breaks the string with seperator “,”
• Example:
<?php
$arr=array('computer', 'department');
echo implode(" ",$arr);
?> return string with space
Output:
• Example:
<?php
$dept[0]="IT";
$dept[1]="Computer";
$dept[2]="Mech"; Copy whole array
$department=$dept;
echo $department[1];
?> Developed By: Amit Lakhani, TFGP Adipur
4.5
Validating user input
Syntax
setcookie(name, value, expire, path, domain);
Example:
<?php
// set the expiration date to one hour ago
setcookie("user", “Amit Lakhani", time()-3600);
?>
Example
<?php
echo $_REQUEST["fname"]; ?>!<br />
?>
Developed By: Amit Lakhani, TFGP Adipur
$_REQUEST example
Form_request.php
<html><body>
<form action="request.php" method="post" >
Name:<input type="text“ name="fname" />
Surname: <input type="text" name="surname" />
<input type="submit" value="Send" />
</form></body></html>
request.php Get the value of input
<?php
echo “Name:”$_REQUEST['fname'];
echo "Surname:”$_REQUEST['surname'];
?>
Developed By: Amit Lakhani, TFGP Adipur
Output of $_REQUEST example
Form_request.php
<html><body>
<form action="<?php $_PHP_SELF ?>" method="post">
</form></body></html>
• Syntax
header(string,replace,http_response_code)
• User Input
• Adding Items
Error Handling
Error handling
• This unit covers….
5.3 Exceptions
<?php
$file=fopen("welcome.txt","r");
?>
If the file does not exist you might get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to
open stream:No such file or directory in
C:\webfolder\test.php on line 2
<?php
if(!file_exists("welcome.txt")) handle
handle error
error using
using die()
die()
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?> Developed By: Amit Lakhani, TFGP Adipur
5.3
Exception Handling
<?php
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}
set_error_handler("customError");
echo($test);
?>
• Exceptions
• Parse errors
• Example:
<html><body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label>Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Upload" />
</form>
</body></html>
<?php
$link=mysql_connect("localhost","root","");
if(!$link)
{
die('Not connected:'.mysql_error());
}
$db=mysql_select_db('upload',$link);
if(!$db)
{ Connect
Connect to
to database
database server
server
die('Database error:‘.mysql_error());
}
• MyISAM • MERGE
• InnoDB • HEAP
Command line
Syntax:
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
password Optional. Specifies the password to log in with.
Default is ""
Developed By: Amit Lakhani, TFGP Adipur
Connecting to database example
$con
$con object
object stores
stores the
the connectionstring
connectionstring
<?php
$con = mysql_connect("localhost",”root",”");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo “Database connection successed”;
// some code
mysql_close($con); Closing
Closing connection
connection
?>
Parameter Description
query Required. SQL query to create or delete
database.
link Optional. If not specified last opened connection
will be used
mysql_select_db(db_name, connection)
Parameter Description
db_name Required. MySQL database name to be selected
connection Optional. If not specified last opened connection
will be used
• Cross join
• Equi-Join
• Non equi join
• The right join
• The full join
• Self join
WAMPSERVER in
Quick launch bar
Write field
name
And its
attributes
here and click
on save or Go
Query executed
{
echo "Error creating database: " mysql_error();
}?> Developed By: Amit Lakhani, TFGP Adipur
Creating table using PHP
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
} Create
Create table
table
else
{
echo "Error creating database: " . mysql_error();
}
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(FirstName varchar(15),LastName varchar(15),Age int)";
mysql_query($sql,$con);
mysql_close($con);?> Developed By: Amit Lakhani, TFGP Adipur
8.2
Manipulating the
table
• Inserting record
• Deleting record
• Updating data
• Searching record
Enter
Enter records
records
Press
Press submit
submit
Inserts
Inserts one
one record
record to
to
database
database
Enter
Enter records
records
Press
Press submit
submit
Inserts
Inserts one
one record
record to
to
database
database
Display
Display all
all records
records
When
When display
display is
is
clicked
clicked
Press
Press search
search
It
It displays
displays selected
selected
record
record
Click
Click on
on the
the link
link
And
And itit will
will display
display
Clicked
Clicked record
record onon
Other
Other page
page
update
update withwith new
new Entries
Entries and
and
click
click on
on Save
Save button
button and
and form
form
will
will call
call mysql_save_detail.php
mysql_save_detail.php
page
page
mysql_close($con);
}
?>
• Creating a table
• Manipulating the table
• Filling the table with data
• Adding links to the table
• Adding data the table
• Displaying information
• Displaying the movie detail
• Editing the database
• Inserting record
• Deleting record
• Editing data
Developed By: Amit Lakhani, TFGP Adipur