PHP MySQL Notes
PHP MySQL Notes
UNIT – I
Introduction to PHP:
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is free to download and use
What is a PHP File?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain HTML
PHP files have extension ".php"
What Can PHP Do?
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You
can also output any text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
Basic PHP Syntax
A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
VSR Govt Degree College,Movva
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to
output the text "Hello World!" on a web page:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
*****************************************************************************************
Variables in PHP
A variable is a special container that you can define, which then “holds” a value, such as a number, string,
object, array, or a Boolean. Variables are fundamental to programming. without variables, you would be forced
to hard-code each specific value used in your scripts.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x
will hold the value 5, and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the
moment you first assign a value to it.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, tota_ volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
Variable names are case-sensitive ($age and $AGE are two different variables) Remember that PHP
VSR Govt Degree College,Movva
// using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; }
myTest();
echo "<p>Variable x outside function is: $x</p>"; ?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>";
?>
You can have local variables with the same name in different functions, because local variables are only
recognized by the function in which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function. To do this, use the global
keyword before the variables (inside the function):
Example:
<?php
$x = 5;
$y = 10;
function myTest() { global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
VSR Govt Degree College,Movva
myTest();
echo $y; // outputs 15
?>
PHP the static Keyword
Normally, when a function is completed /executed, all of its variables are deleted. However, sometimes we want
a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<?php
function myTest() { static $x = 0; echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained from the last time
the function was called.
Note: The variable is still local to the function.
***********************************************************************************
PHP Data Types
Variables can store data of different types, and different data types can do different things. PHP supports the
following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string is a sequence of characters, like "Hello world!". A string can be any text inside quotes. You can use
single or double quotes:
VSR Govt Degree College,Movva
<?php
$x = "Hello world!";
$y = 'Hello world!'; echo $x;
echo "<br>"; echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with
0x) or octal (8-based - prefixed with 0)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
OUTPUT:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
***********************************************************************************
PHP Object
An object is a data type which stores data and information on how to process that data. In PHP, an object must
be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain
VSR Govt Degree College,Movva
// create an object
$herbie = new Car();
<?php
$x = "Hello world!";
$x = null; var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and resources
external to PHP.
A common example of using the resource data type is a database call.
***********************************************************************************
PHP Operators and Expressions
Operators are used to perform operations on variables and values. PHP divides the operators in the following
groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
VSR Govt Degree College,Movva
Array operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
»
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the Try it
same type »
> Greater than $x > $y Returns true if $x is greater than $y Try it
»
< Less than $x < $y Returns true if $x is less than $y Try it
»
>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y Try it
equal to »
<= Less than or $x <= $y Returns true if $x is less than or equal to $y Try it
equal to »
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero,
depending on if $x is less than, equal to, or greater than
$y. Introduced in PHP 7.
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to
decrement a variable's value.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
PHP String Operators
PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
VSR Govt Degree College,Movva
myTest();
?>
Predefined Constants
PHP automatically provides some built-in constants for you. For example, the constant FILE returns the name of
the file that the PHP engine is currently reading. The constant LINE returns the current line number of the
file. These are but two examples of what are called “magic constants,” because they are not statically predefined
and instead change depending on the context in which they are used.
***********************************************************************************
PHP Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different conditions. You can use
conditional statements in your code to do this.
In PHP we have the following conditional statements:
if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and another code if that condition is
false
if...elseif .... else statement - executes different codes for more than two conditions
switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
</html>
PHP - The if...else Statement
The if. ........ else statement executes some code if a condition is true and another code if that condition
is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!"
otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif............. else Statement
The if....elseif. else statement executes different codes for more than two conditions.
Syntax
if (condition) {
Code to be executed if this condition is true;
} elseif (condition) {
Code to be executed if this condition is true;
} else {
Code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and "Have a good
day!" if the current time is less than 20. Otherwise it will output "Have a good night!":
<!DOCTYPE html>
<html>
<body>
VSR Govt Degree College,Movva
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>"; if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>
PHP 5 switch Statement
The switch statement is used to perform different actions based on different conditions. Use the switch statement
to select one of many blocks of code to be executed.
Syntax
switch (n) { case label1:
code to be executed if n=label1; break;
case label2:
code to be executed if n=label2; break;
case label3:
code to be executed if n=label3; break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The
value of the expression is then compared with the values for each case in the structure. If
there is a match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no match is found.
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red"; switch ($favcolor) {
VSR Govt Degree College,Movva
case "red":
echo "Your favorite color is red!"; break;
case "blue":
echo "Your favorite color is blue!"; break;
case "green":
echo "Your favorite color is green!"; break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
Using the ?: Operator
The ?: or ternary operator is similar to the if statement, except that it returns a value derived from one of two
expressions separated by a colon. This construct provides you with three parts of the whole, hence the name
ternary. The expression used to generate the returned value depends on the result of a test expression:
(expression) ? returned_if_expression_is_true : returned_if_expression_is_false;
If the test expression evaluates to true, the result of the second expression is returned; otherwise, the value of the
third expression is returned.
Example:
<?php
$mood = “sad”;
$text = ($mood == “happy”) ? “I am in a good mood!” : “I am in a $mood mood.”; echo “$text”;
?>
PHP Looping / Iterative Statements
Scripts can also decide how many times to execute a block of code. Loop statements are specifically designed to
enable you to perform repetitive tasks because they continue to operate until a specified condition is achieved or
until you explicitly choose to exit the loop.
Often when you write code, you want the same block of code to run over and over again in a row. Instead of
adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
VSR Govt Degree College,Movva
$x++;
} while ($x <= 5);
?>
The PHP for Loop
PHP for loops execute a block of code a specified number of times. The for loop is used when you know in
advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) { code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to
FALSE, the loop ends.
increment counter: Increases the loop counter value The example below displays the numbers from 0 to 10:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value) { code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array ($colors):
<?php
$colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) {
echo "$value <br>";
}
?>
***********************************************************************************
Code Blocks and Browser Output
Imagine a script that outputs a table of values only when a variable is set to the Boolean value true. The
following code shows a simplified HTML table constructed with the code block of an if statement.
VSR Govt Degree College,Movva
<?php
$display_prices = true; if ($display_prices) {
echo “<table border=\”1\”>\n”; echo “<tr><td colspan=\”3\”>”; echo “today’s prices in dollars”; echo
“</td></tr>”;
echo “<tr><td>\$14.00</td><td>\$32.00</td><td>\$71.00</td></tr>\n”; echo “</table>”;
}
?>
If the value of $display_prices is set to true in line 2, the table is printed. Put these lines into a text file called
testmultiecho.php and place this file in your web server document root.
There’s nothing wrong with the way this is coded, but you can save yourself some typing by simply slipping
back into HTML mode within the code block.
<?php
$display_prices = true; if ($display_prices) {
?>
<table border=”1”>
<tr><td colspan=”3”>today’s prices in dollars</td></tr>
VSR Govt Degree College,Movva
<tr><td>$14.00</td><td>$32.00</td><td>$71.00</td></tr>
</table>
<?php
}
?>
The important thing to note here is that the shift to HTML mode on line 4 occurs only if the condition of the if
statement is fulfilled. This can save you the bother of escaping quotation marks and wrapping our output in
echo() statements. This approach might, however, affect the readability of the code in the long run, especially if
the script grows larger.
-------XXXX--------
UNIT II
Working with Functions
What is function?
A function is a self-contained block of code that can be called by your scripts. When called, the function’s code
is executed and performs a particular task. You can pass values to a function, which then uses the values
appropriately—storing them, transforming them, displaying them, whatever the function is told to do. When
finished, a function can also pass a value back to the original code that called it into action.
1. Defining functions:
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
A user defined function declaration starts with the word "function":
Syntax
function functionName() { code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does! Function names are NOT case-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the
beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function
outputs "Hello world!". To call the function, just write its name:
<?php
function writeMsg() { echo "Hello world!";
}
VSR Govt Degree College,Movva
the script. Within a function, if you attempt to use a variable with the same name, you will only set or access a
local variable.
<?php
$life = 42;
function meaningOfLife()
{
echo “The meaning of life is “.$life”;
}
meaningOfLife();
?>
Put these lines into a text file called scopetest2.php and place this file in your web server document root. When
you access this script through your web browser, it should look like
Fig: Variables Defined Outside Functions Are Inaccessible from Within a Function by Default.
As you might expect, the meaningOfLife() function does not have access to the $life variable in line 2; $life is
empty when the function attempts to print it. On the whole, this is a good thing because it saves you from
potential clashes between identically named variables, and a function can always demand an argument if it needs
information about the outside world. Occasionally, you might want to access an important variable from within a
function without passing it in as an argument. This is where the global statement comes into play.
<?php
$life = 42;
function meaningOfLife()
{
global $life;
echo “The meaning of life is “.$life”;
}
VSR Govt Degree College,Movva
meaningOfLife();
?>
Put these lines into a text file called scopetest3.php and place this file in your web server document root. When
you access this script through your web browser, it should look like.
the variable’s value (10). Any changes made to an argument in these cases change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the argument name in the function
definition, as shown in line 2.
Working with Array in PHP
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like
this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but
300?The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index
number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
Ex: $cars = array("Volvo", "BMW", "Toyota"); In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
1. The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
2. The index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example Program:- The following example creates an indexed array named $cars, assigns three elements to it,
and then prints a text containing the array values
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
VSR Govt Degree College,Movva
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an
associative array:
1. $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");2. $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays. PHP understands multidimensional arrays
that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to
manage for most people.
A multidimensional array holds more than one series of these key/value pairs.Example.
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2), array("Land Rover",17,15)
);
3. Some Array-Related Functions
More than 70 array-related functions are built in to PHP. Some of the more common (and useful) functions are
described briefly below.
1. count() and sizeof()—Each of these functions counts the number of elements in an array; they are aliases of
eachOther. Given the following array.
Example: $colors = array(“blue”, “black”, “red”, “green”);
both count($colors); and sizeof($colors); return a value of 4.
2. each() and list()—These functions usually appear together, in the context of stepping through an array and
returning its keys and values.
Example:
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
3. foreach()—This control structure (that looks like a function) is used to step through an array.
Example:
foreach ($characters as $c) { while (list($k, $v) = each ($c)) { echo “$k ... $v <br/>”;
}
VSR Govt Degree College,Movva
echo “<hr/>”;
}
4. reset()—This function rewinds the pointer to the beginning of an array.example: reset($character);
This function proves useful when you are performing multiple manipulations on an array, such as sorting,
extracting values, and so forth.
5. array_push()—This function adds one or more elements to the end of an existing array. example:
array_push($existingArray, “element 1”, “element 2”, “element 3”);
6. array_pop()—This function removes (and returns) the last element of an existing array.
Example: $last_element = array_pop($existingArray);
7. array_unshift()—This function adds one or more elements to the beginning of an existing array.
Example: array_unshift($existingArray, “element 1”, “element 2”, “element 3”);
array_shift()—This function removes (and returns) the first element of an existing array. Example:
$first_element = array_shift($existingArray);
8. array_merge()—This function combines two or more existing arrays.
Example: $newArray = array_merge($array1, $array2);
9. array_keys()—This function returns an array containing all the key names within a given array.
Example: $keysArray = array_keys($existingArray);
10. array_values()—This function returns an array containing all the values within a given array.
Example: $valuesArray = array_values($existingArray);
11. shuffle()—This function randomizes the elements of a given array. The syntax of this function is simply as
follows: shuffle($existingArray).
Working with Objects
Introduction:
Programmers use objects to store and organize data. Object-oriented programming is a type of programming in
which the structure of the program (or application) is designed around these objects and their relationships and
interactions. Object-oriented programming structures are found in many programming languages, and are also
evident in PHP. In fact, many PHP programmers—especially those coming from a highly object-oriented
programming background— choose to develop PHP applications in an object-oriented way.
PHP | Objects
An Object is an individual instance of the data structure defined by a class. We define a class once and then
make many objects that belong to it. Objects are also known as instances.
Creating an Object:
Following is an example of how to create object using new operator.
class Books {
// Members of class Books
VSR Govt Degree College,Movva
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
The following syntax used are for the following program elaborated in the example given below:
Example:
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price."<br>";
}
function setTitle($par){
VSR Govt Degree College,Movva
$this->title = $par;
}
function getTitle(){
echo $this->title."<br>" ;
}
}
}
// now constructor is called automatically
// because we have initialized the object
// or class Bird.
$Geek = new GeeksforGeeks("GeeksforGeeks");
echo $Geek->Geek_name;
?>
Working with PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports only 256-character
set and so that it does not offer native Unicode support. There are 4 ways to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string in
PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use double
backslash (\\). All the other instances with backslash such as \r or \n, will be output same as they specified
instead of having any special meaning.
Following some examples are given to understand the single quoted PHP String in a better way:
Example 1
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
Hello text within single quote
We can store multiple line text, special characters, and escape sequences in a single-quoted PHP string.
Example 2
1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
VSR Govt Degree College,Movva
For Example
Valid Example
1. <?php
2. $str = <<<Demo
3. It is a valid example
4. Demo; //Valid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
Output:
It is a valid example
Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, which means identifier must
not be indented. The identifier must begin from the new line.
1. <?php
2. $str = <<<Demo
3. It is Invalid example
4. Demo; //Invalid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
This code will generate an error.
Output:
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\xampp\PMA\heredoc.php o
Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with three less than
symbols <<< followed by an identifier. But here identifier is enclosed in single-quote, e.g. <<<'EXP'. Newdoc
follows the same rule as heredocs.
The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas heredoc is
a double-quoted string.
Example-1:
1. <?php
2. $str = <<<'DEMO'
3. Welcome to javaTpoint.
4. Learn with newdoc example.
5. DEMO;
6. echo $str;
7. echo '</br>';
VSR Govt Degree College,Movva
8.
9. echo <<< 'Demo' // Here we are not storing string content in variable str.
10. Welcome to javaTpoint.
11. Learn with newdoc example.
12. Demo;
13. ?>
Output:
Welcome to javaTpoint. Learn with newdoc example.
Welcome to javaTpoint. Learn with newdoc example.
UNIT - III
Working with FORMS
Creating a form
The example below displays a simple HTML form with two input fields and a submit button:
<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>
VSR Govt Degree College,Movva
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP
filenamed "welcome.php". The form data is sent with the HTTP POST method.
Accessing / Reading form Data
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Accessing Form Input with User-Defined Arrays:
HTML forms are required, when you want to collect some data from the site visitor. For example, during user
registration you would like to collect information such as name, e-mail address, credit card etc., The following
are theform elements.
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multiline input control (text area)
<label> Defines a label for an <input> element
<fieldset> Groups related elements in a form
<legend> Defines a caption for a <fieldset> element
<select> Defines a drop-down list
<optgroup> Defines a group of related options in a drop-down list
<option> Defines an option in a drop-down list
<button> Defines a clickable button Example:
<!DOCTYPE html>
<html>
<head>
<title>An HTML form with checkboxes</title>
</head>
<body>
<form action=”send_formwithcb.php” method=”POST”>
<p><label>Name:</label><br/>
<input type=”text” name=”user” /></p>
VSR Govt Degree College,Movva
<fieldset>
<legend>Select Some Products:</legend><br/>
<input type=”checkbox” id=”tricorder”name=”products[]” value=”Tricorder”>
<label for=”tricorder”>Tricorder</label><br/>
<input type=”checkbox” id=”ORAC_AI”name=”products[]” value=”ORAC AI”>
<label for=”ORAC_AI”>ORAC AI</label><br/>
<input type=”checkbox” id=”HAL_2000”name=”products[]” value=”HAL 2000”>
<label for=”HAL_2000”>HAL 2000</label>
</fieldset>
<button type=”submit” name=”submit” value=”submit”>Submit Form</button>
</form>
</body>
</html>
Combining HTML and PHP code on a single Page
PHP is an HTML embedded server side scripting language. Much of its syntax is borrowed from C, Java and
Perl with a couple of unique PHP specific features thrown in. The goal of the language is to allow web
developers to write dynamically generated pages quickly.
PHP in HTML:
When building a complex page, at some point you will be face with the need to combine PHP with HTML to
achieve your needed results. There are two ways to HTML on your PHP page.
1) The first way is to put the HTML outside of your PHP tag. You can even put it in the middle of your close
and reopenthe <? php and ?> tags. Here is an example of putting the HTML outside of the tags.
<html>
<title> HTML with PHP</title>
<h1> example one </h1>
<? php
// your php code goes here
?>
<b> here is some more HTML </b>
<? php
// some more php code here
?>
</body>
</html>
As you can see you can use any HTML you want without doing anything special or extra in your .php file, as
long as it is outside of the PHP tags.
VSR Govt Degree College,Movva
2. The second way to use HTML with php is by using PRINT or EACH. By using this method you can
include the HTML outside of the PHP tags. This is a nice quick method if you only have a line or so to do. Here
is an example:
<? Php
Eacho”<html>”;
Eacho”<title> HTML with php </title>”;
// your php code goes here
Print “<i> print works too!</i>;
?>
Using Hidden Fields to Save State
A hidden field behaves the same as a text field, except that the user cannot see it unless he views the HTML
source ofthe document that contains it. Hidden fields are typically used for three purposes.
1. Tracking users as they move around within a site.
2. Hidden fields are used to provide predefined input to a server side program when a variety of static
HTML pages actas front ends to the same program on the server.
3. Hidden fields are used to store contextual information in pages that are dynamically generated.
<?php
$num_to_guess = 42;
$num_tries = (isset($_POST[num_tries])) ? $num_tries + 1 : 0;
$message = "";
if (!isset($_POST[guess])) {
$message = "Welcome to the guessing machine!";
} elseif ($_POST[guess] > $num_to_guess) {
$message = "$_POST[guess] is too big! Try a smaller number";
} elseif ($_POST[guess] < $num_to_guess) {
$message = "$_POST[guess] is too small! Try a larger number";
} else { // must be equivalent
$message = "Well done!";
}
$guess = $_POST[guess];
?>
<html>
<head>
<title>Listing 9.8 Saving state with a hidden field</title>
</head>
<body>
VSR Govt Degree College,Movva
</body>
</html>
This is a simple PHP script, so we put a form that inputs a name and comment. In the PHP script we check if the
server request method is post because we don’t want this code to execute if user hasn’t submitted the form
through POST method, which is only possible if he submit the form.
Next, we store the values received in $comment and $name variables. Then we check if they are not empty, that
is they have some value, then we redirect the visitor to thankyou.html page.
thankyou.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>Thank you!</p>
</body>
</html>
So this is how you redirect to another page using header() function in PHP.
The thank you page contains a simple thank you message in html file, since it is just for display.
Sending Mail on Form Submission
Sending Mail to specific email becomes a global issue for website development. Online communication for any
organization with customers or users is done either by emailing them or through comments. These organizations
or companies use feedback or contact form to communicate with users.
Through these forms user is able to send his/her suggestion or feedback via email to respective organization.
Here, we will show you, how to use mail() function of PHP to send information’s like,
suggestions/messages to specific email address on form submission.
we used following PHP mail() function with four parameters to send email as follows: mail("$to", $subject,
$message, $headers);
o Here, $to variable is to store reciever’s email id.
o $subject is a variable to store mail subject.
o $message is a variable to store user’s message.
$headers contains other email parameters like BCc, Cc etc.
Working with File Uploads
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are
uploaded intoa temporary directory and then relocated to a target destination by a PHP script.
VSR Govt Degree College,Movva
Information in the phpinfo.php page describes the temporary directory that is used for file uploads as
upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize.
These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps −
1. The user opens the page containing a HTML form featuring a text files, a browse button and a submit
button.
2. The user clicks the browse button and selects a file to upload from the local PC.
3. The full path to the selected file appears in the text filed then the user clicks the submit button.
4. The selected file is sent to the temporary directory on the server.
5. The PHP script that was specified as the form handler in the form's action attribute checks that the
file has arrived and then copies the file into an intended directory.
6. The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have permissions set that
enablefile writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Working with Cookies and User Sessions
Cookies in PHP.
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the server,
cookie is embedded with request. Such way, cookie can be received at the server side.
A session is a way to store information (in variables) to be used across multiple pages.
VSR Govt Degree College,Movva
?>
<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>
<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click here</a>.
</p>
------xxxxx------
UNIT – IV
MYSQL
INTRODUCTION
MySQL is an open-source, fast reliable, and flexible relational database management system, typically used with
PHP. This chapter is an introductory chapter about MySQL, what is MySQL, and the main features of MySQL
are described here.
WHAT IS MYSQL
MySQL is a database system used for developing web-based software applications.
MySQL used for both small and large applications.
MySQL is a relational database management system (RDBMS).
MySQL is fast, reliable, and flexible and easy to use.
MySQL supports standard SQL (Structured Query Language).
MySQL is free to download and use.
MySQL was developed by Michael Widenius and David Axmark in 1994.
MySQL is presently developed, distributed, and supported by Oracle Corporation.
MySQL Written in C, C++.
MAIN FEATURES OF MYSQL
MySQL server design is multi-layered with independent modules.
MySQL is fully multithreaded by using kernel threads. It can handle multiple CPUs if they are available.
MySQL provides transactional and non-transactional storage engines.
MySQL has a high-speed thread-based memory allocation system.
MySQL supports in-memory heap table.
MySQL Handles large databases.
MySQL Server works in client/server or embedded systems.
MySQL Works on many different platforms.
USES OF MYSQL
Some of the most famous websites like Facebook, Wikipedia, Google (not for search), YouTube, Flickr.
VSR Govt Degree College,Movva
Content Management Systems (CMS) like WordPress, Drupal, Joomla, phpBB etc.
A large number of web developers worldwide are using MySQL to develop web applications.
THE IMPORTANCE OF GOOD DATABASE DESIGN
Good database design is crucial for a high performance application, just like an aerodynamic body is important
to a racecar. If the racecar doesn't have smooth lines, it will produce drag and go slower. The same holds true for
databases. If a database doesn't have optimized relationships—normalization—it won't be able to perform as
efficiently as possible.
Beyond performance is the issue of maintenance. Your database should be easy to maintain. This includes
storing a limited amount (if any) of repetitive data. If you have a lot of repetitive data and one instance of that
data undergoes a change (such as a name change), that change has to be made for all occurrences of the data. To
eliminate duplication and enhance your ability to maintain the data, you would create a table of possible values
and use a key to refer to the value. That way, if the value changes names, the change occurs only once—in the
master table. The reference remains the same throughout other tables.
MYSQL DATATYPES
A database table contains multiple columns with specific data types such as numeric or string. MySQL provides
more data types other than just numeric and string. Each data type in MySQL can be determined by the
following characteristics:
The kind of values it represents.
The space that takes up and whether the values are a fixed-length or variable length.
The values of the data type can be indexed or not.
How MySQL compares the values of a specific data type.
VSR Govt Degree College,Movva
FLOAT(M,D) − A floating-point number that cannot be unsigned. You can define the display length (M) and
the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals and
10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.
DOUBLE(M,D) − A double precision floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is the
number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
DECIMAL(M,D) − An unpacked floating-point number that cannot be unsigned. In the unpacked decimals,
each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is
required. NUMERIC is a synonym for DECIMAL.
DATE AND TIME TYPES
The MySQL date and time datatypes are as follows −
DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th,
1973 would be stored as 1973-12-30.
DATETIME − A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01
00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored
as 1973-12-30 15:30:00.
TIMESTAMP − A timestamp between midnight, January 1 st, 1970 and sometime in 2037. This looks like the
previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December
30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
TIME − Stores the time in a HH:MM:SS format.
YEAR(M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example YEAR(2)),
YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then YEAR can be 1901 to 2155.
The default length is 4.
STRING TYPES
Although the numeric and date types are fun, most data you'll store will be in a string format. This list describes
the common string datatypes in MySQL.
CHAR(M) − A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-
padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1.
VARCHAR(M) − A variable-length string between 1 and 255 characters in length. For example,
VARCHAR(25). You must define a length when creating a VARCHAR field.
BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects" and
are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT
also hold large amounts of data. The difference between the two is that the sorts and comparisons on the stored
data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with
BLOB or TEXT.
VSR Govt Degree College,Movva
TINYBLOB or TINYTEXT − A BLOB or TEXT column with a maximum length of 255 characters. You do
not specify a length with TINYBLOB or TINYTEXT.
MEDIUMBLOB or MEDIUMTEXT − A BLOB or TEXT column with a maximum length of 16777215
characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.
LONGBLOB or LONGTEXT − A BLOB or TEXT column with a maximum length of 4294967295
characters. You do not specify a length with LONGBLOB or LONGTEXT.
ENUM − An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of
items from which the value must be selected (or it can be NULL). For example, if you wanted your field to
contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or
NULL) could ever populate that field.
CREATION TABLE
The table creation command requires the following details −
Name of the table
Name of the fields
Definitions for each field
Syntax
Here is a generic SQL syntax to create a MySQL table −
CREATE TABLE table_name (column_name column_type);
create table tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT,
tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( tutorial_id )
);
Here, a few items need explanation −
Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user
will try to create a record with a NULL value, then MySQL will raise an error.
Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to
the id field.
Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple columns
separated by a comma to define a primary key.
Creating Tables Using PHP Script
PHP uses mysqli query() or mysql_query() function to create a MySQL table. This function takes two
parameters and returns TRUE on success or FALSE on failure.
VSR Govt Degree College,Movva
Syntax
$mysqli->query($sql,$resultmode)
1 $sql
Required - SQL query to create a MySQL table.
2 $resultmode
Optional - Either the constant MYSQLI_USE_RESULT or
MYSQLI_STORE_RESULT depending on the desired behavior. By default,
MYSQLI_STORE_RESULT is used.
Example
Try the following example to create a table −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Creating MySQL Table</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
$mysqli->close();
?>
</body>
</html>
Output
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Table tutorials_tbl created successfully.
WHAT IS INSERT INTO?
INSERT INTO is used to store data in the tables. The INSERT command creates a new row in the table to store
data. The data is usually supplied by application programs that run on top of the database.
Basic syntax
Let’s look at the basic syntax of the INSERT INTO MySQL command:
INSERT INTO `table_name`(column_1,column_2,...) VALUES (value_1,value_2,...);
HERE
INSERT INTO `table_name` is the command that tells MySQL server to add a new row into a table
named `table_name.`
(column_1,column_2,…) specifies the columns to be updated in the new MySQL row
VALUES (value_1,value_2,…) specifies the values to be added into the new row
INSERT INTO `members` (`full_names`,`gender`,`physical_address`,`contact_number`) VALUES
(Srinivas Vellanki','Male','Kakinada',9848017388);
THE MYSQL SELECT STATEMENT
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
VSR Govt Degree College,Movva
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all
the fields available in the table, use the following syntax:
SELECT * FROM table_name;
THE MYSQL WHERE CLAUSE
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
THE MYSQL UPDATE STATEMENT
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
THE MYSQL AND, OR AND NOT OPERATORS
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
VSR Govt Degree College,Movva
MSQL and MySQLi are PHP database extensions implemented by using PHP extension framework. PHP
database extensions are used to write PHP code for accessing the database. They expose database API to provide
interfaces to use database functions.
MySQL extension is deprecated and will not be available in future PHP versions. It is recommended to use the
MySQLi extension with PHP 5.5 and above.
MySQL MySQLi Difference
There are too many differences between these PHP database extensions. These differences are based on some
factors likeperformance, library functions, features, benefits, and others.
MySQL MySQLi
MySQL extension added in PHP version 2.0. MySQLi extension added in PHP 5.5 and
and deprecated as of PHP 5.5.0. will work on MySQL 4.1.3 or above.
MySQL provides the procedural interface. MySQLi provides both procedural and
object-oriented interface.
MySQL extension does not support stored MySQLi supports store procedure.
procedure.
MySQL extension lags in security and other MySQLi extension is with enhanced security
special features, comparatively. and improved debugging.
Transactions are handled by SQL queries MySQLi supports transactions through API.
only.
following:
$conn->close();
Executing Queries
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,lastname VARCHAR(30) NOT NULL, email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
WORKING WITH MYSQL DATA
a) Inserting Data with PHP
After a database and a table have been created, we can start adding data in them. Here are some syntax rules to
follow:
The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
VSR Govt Degree College,Movva
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)Example:
<?php
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$servername = "localhost";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
b) Retrieving Data with PHP.
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
VSR Govt Degree College,Movva