Professional Documents
Culture Documents
PHP & Mysql
PHP & Mysql
Text Editor
Web
browser
What is a PHP File?
• PHP files can contain text, HTML tags and
scripts
".php3", or ".phtml"
/* PHP Code
*/
?>
</body>
</html>
Comments
Single-line comments: # and //
/*
* this is a multi-line PHP
* comment block
*/
?>
Echo
echo is not actually a function (it is a
language construct)
echo (arg1, arg2... )
Example
<?php
echo “Hello This is Sample
Text”;
?>
Echo
Echo accepts multiple arguments
<?php
echo “Velalar“, “Engineering",
"College”;
?>
Print
The command print is very similar to echo, with
two important differences
-x Negation Opposite of x
x !== y Not identical True if x is not equal to y, or they are not of same type
x=6
x and y And True if both x and y are true y=3
(x < 10 and y > 1) returns true
x=6
x or y Or True if either or both x and y are true y=3
(x==6 or y==5) returns true
x=6
x xor y Xor True if either x or y is true, but not both y=3
(x==6 xor y==3) returns false
x=6
x && y And True if both x and y are true y=3
(x < 10 && y > 1) returns true
x=6
x || y Or True if either or both x and y are true y=3
(x==5 || y==5) returns false
x=6
!x Not True if x is not true y=3
!(x==y) returns true
Automatic type conversion
PHP does a good job of automatically converting
types when necessary
$pi = 3 + 0.14159;
Syntax
function
functionName(arg1,arg2,….argn)
{
code to be executed;
}
<html>
<body>
<?php
function writeName()
{
echo “Sukhesh Raj";
}
echo "My name
is ";
writeName();
?>
</body>
</html>
Function – Return the values
Function return a value, using the return
statement
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
PHP functions:
Array functions HTTP functions
Calendar functions LibXML
Date functions functions Mail
Directory functions functions Math
Error functions functions Misc
Filesystem functions functions
Filter functions MySQL functions
FTP functions SimpleXML
functions
String functions
XML Parser
functions
Arrays
•Index Arrays
•Associative Arrays
•Multidimensional
Arrays
Arrays
Arrays are known as compound data types
Can hold multiple values indexed by numbers or
strings
Indexed Arrays
Arrays with numerical keys
Associative Arrays
keys can also be named with strings
Multidimensional arrays
Arrays containing one or more arrays
Indexed
Arrays
To create an empty array $a = array()
Array with values
$arr_name=array(“value1”,”value2”,”val
ue3”);
Ex:
<?php
$cars=array("Saab","Volvo","BMW”)
;
?>
$myArray = array(0 => 10, 1 => 20, 2 =>
30) ;
Assign the index manually
<?php
$cars[0]="Saab"
;
$cars[1]="Volvo
";
$cars[2]="BMW
";
$cars[3]="Toyot
a";
?>
Associative
Arrays
The key portion of an array can also
consist of character strings
$array_name*key+=“value”;
Traversing
Array
<?php
$myArray = array(‘sno' => 1, ‘rollno' =>
“12itr001”, 'fname' => "Peter", 'initial' =>
"B",
'lname' => "MacIntyre", 'phone' =>
“04294-226570") ; foreach ($myArray as $key
=> $value)
{
echo "the Key is: " . $key . " and its value is: " .
$value . "<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.
Example
Double quote
Allows variable expansion (variable content
insertion)
Single Quote
Does not allows variable expansion
Double quote
<?php
$eng = “Engineering" ;
$place = “Thindal" ;
$string = “Velalar $eng College,
$place"; echo $string ."<br>";
$string = "He said \"go away\" to
me" ;
$eco $string;
?>
Single Quote
<?php
$eng = “Engineering" ;
$place = “Thindal" ;
$string = ‘Velalar $eng .’College,’.
$place’;
echo $string
$string = ‘Velalar’. $eng .’College,’.
$place’; echo $string ;
str_word_count(string)
counts the number of words in a given string
Setcookie(‘cookiename’,’’,time()-600);
Another way
Setcookie(‘cookiename’,’’);
Setcookie(‘cookiename’, FALSE);
SESSION
Session variables hold information about
one single user
The data is available to all pages in
one application
Session data is stored on the server
Benefits over cookies
Session are generally more secure
It will store more information
It will work even cookies is not enabled
Starting a PHP Session
First start session using session_start()
session_start() function must appear
BEFORE the
<html> tag
Example
<?php session_start(); ?>
<html>
<body>
……..
</body>
</html>
Creating a Session
Record data by assigning values to the
$_SESSION array
$_SESSION*‘Sess_var_name’+=value;
Example
$_SESSION*‘username’+=“
Raja”;
Delete a Session
Variable
To delete some session data the
following functions are used
unset()
used to free the specified session
variable
session_destroy()
To reset session and delete all stored
session data
SSI – Server Side Include
Include /
require
PHP include and require Statements
To insert the content of one PHP file into
another PHP file before the server
executes it
include and require statements are
used to insert useful codes written in
other files
require will produce a fatal error and stop
the script
include will only produce a warning and
the script will continue
PHP and
MySQL
Data base connectivity and Data
manipulations
Introduction to Database
A database is a collection of data
Databases implemented through a
computer are created within software
PHP+MySQL
PHP combined with MySQL are
cross-platform
Connecting to MySQL
mysqli_connect() / mysql_connect()
It open a new connection to the MySQL server
Syntax
mysqli_connect(host,username,password,dbname,port,
socket);
Parameter Description
host Optional. Either a host name or an IP address
mysqli_query(connection,query,resultm
ode);
function executes a query on a MySQL database
Connection Specifies the MySQL connection to use
Optional.
A constant. Either:
resultmode •MYSQLI_USE_RESULT (Use this if we have to retrieve large
amount of data)
•MYSQLI_STORE_RESULT (This is default)
Handle with Database
Create Database
CREATE DATABASE db_name
Select the created Database
mysqli_select_db(db_name,conne
ction)
Drop a Database
<?php
$con =
mysqli_connect("localhost",“root","");
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
else {
echo "Database connected“; }
if (mysqli_query($con,"CREATE DATABASE
my_db"))
{ echo "Database
created“; } else
{ echo "Error creating database: " .
mysql_error();
}
Output
db_connection.php
index.php
<?php
function OpenCon()
{ <?php
$dbhost = "localhost"; include 'db_connection.php';
$dbuser = "root"; $conn = OpenCon();
$dbpass = "1234"; echo "Connected Successfully";
$db = "vcet"; CloseCon($conn);
$conn = new mysqli($dbhost, ?>
$dbuser, $dbpass,$db) or
die("Connect failed: %s\n". $conn ->
error); Output
return $conn;
}
function CloseCon($conn)
{
$conn -> close();
}
?>
MySQL Data types
There are three main
types
Text
Numbers
Dates/Times
Tex
Ttype Size Description
CHAR[Length] Length bytes A fixed-length field from 0 to
255 characters long.
VARCHAR(Length) String length + 1 A fixed-length field from 0 to 255
bytes characters long.
TINYTEXT String length + 1 A string with a maximum length
bytes of 255 characters
TEXT String length + 2 A string with a maximum length
bytes of 65,535 characters.
MEDIUMTEXT String length + 3 A string with a maximum length
bytes of 16,777,215 characters.
LONGTEXT String length + 4 A string with a maximum length
bytes of 4,294,967,295 characters.
TINYINT[Length] 1 byte Range of -128 to 127 or 0 to 255
unsigned.
SMALLINT[Length] 2 bytes Range of -32,768 to 32,767 or 0 to
65,535 unsigned.
Number
Type Size Description
INT[Length] 4 bytes Range of -2,147,483,648 to
2,147,483,647 or 0 to
4,294,967,295 unsigned
BIGINT[Length] 8 bytes Range of -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 or 0
to 18,446,744,073,709,551,615
unsigned
FLOAT 4 bytes A small number with a
floating decimal point.
DOUBLE[Length, 8 bytes A large number with a
Decimals] floating decimal point.
DECIMAL[Length, Length +1 bytes or A DOUBLE stored as a string,
Decimals] Length + 2 bytes allowing for a fixed decimal
point.
Date and Time
Type Size Description
// Create table
$sql = "CREATE TABLE
Persons (
FirstName
varchar(15),
LastName
varchar(15), Age int
)";
// Execute query
mysqli_query($con,
$sql);
INSERT DATA
INSERT INTO table_name
VALUES (value1, value2,
value3,...)
mysqli_fetch_array()
function fetches a result row as an
associative array, a numeric array, or
both
mysqli_fetch_row()
function fetches one row from a result-set
and returns it as an enumerated array
WHERE
WHERE clause is used to extract only those
records that fulfill a specified criterion
Syntax
SELECT
column_name(s)
FROM table_name
WHERE column_name = value
text/plain Spaces are converted to "+" symbols, but no special characters are encoded
Upload (File/Image)
$_FILES System array containing the
uploaded file inform
$_FILES['file']['name']
The original name of the file on the client machine
$_FILES['file']['type']
The mime type of the file (such as “image/jpeg”)
$_FILES['file']['size']
The size, in bytes, of the uploaded file
$_FILES['file']['tmp_name']
The temporary filename of the file in which the
uploaded file was stored on the server
$_FILES['file']['error']
Any error code associated with this file uploadation
Move a File to Destination
move_uploaded_file(file,newloc)
Used to move the uploaded file to
destination
file - Specifies the file to be moved
newloc - Specifies the new location for
the file
Check Whether file exist or not
file_exists(loc/filename)
function checks whether file/ directory
exists or not
Example Upload Form : sample.php
<html>
<body>
<form action="upload.php"
method="post"
enctype="multipart/form-data">
<input type="file" name="f" /><br>
<input type="submit" name="submit"
value="Submit">
</form>
</body>
</html>
Upload.php
<?php
if ($_FILES["f"]["error"] > 0)
{
echo "Error: " . $_FILES["f"]["error"] . "<br>";
}
else
if(file_exists("up/".$_FILES['f']['name']))
{
echo "FILE ALREADY EXISTS";
}
else
move_uploaded_file($_FILES['f']['tmp_name'],"up/".$_FILES['f']['name']);
?>