0% found this document useful (0 votes)
5 views58 pages

PHP MySQL Notes

This document provides an introduction to PHP, covering its definition, capabilities, and basic syntax. It explains PHP variables, their scope, data types, operators, and constants, emphasizing how PHP handles different data types and operations. The document serves as a foundational guide for understanding PHP programming concepts and syntax.

Uploaded by

rajanikanthmeka4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views58 pages

PHP MySQL Notes

This document provides an introduction to PHP, covering its definition, capabilities, and basic syntax. It explains PHP variables, their scope, data types, operators, and constants, emphasizing how PHP handles different data types and operations. The document serves as a foundational guide for understanding PHP programming concepts and syntax.

Uploaded by

rajanikanthmeka4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

VSR Govt Degree College,Movva

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

variable names are case-sensitive!


Output Variables
The PHP echo statement is often used to output data to the screen. The following example will show how to
output text and a variable:
Example-1:
<?php
$txt = "Welcome"; echo "I love $txt!";
?>
The following example will produce the same output as the example above: Example-2:
<?php
$txt = "Welcome"; echo "I love " . $txt . "!";
?>
Example-3:
The following example will output the sum of two variables:
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically
converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable
before using it.
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three
different variable scopes:
 local
 global
 static
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
<?php
$x = 5; // global scope
function myTest() {
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.

A Boolean represents two possible states: TRUE or FALSE.


$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of
this tutorial.
***********************************************************************************
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
<?php
$cars = array("Volvo","BMW","Toyota"); var_dump($cars);
?>

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

properties and methods:


<?php class Car {
function Car() {
$this->model = "VW";
}
}

// create an object
$herbie = new Car();

// show object properties echo $herbie->model;


?>

PHP NULL Value


Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable
that has no value assigned to it. If a variable is created without a value, it is automatically assigned a value of
NULL. Variables can also be emptied by setting the value to NULL:

<?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.

Operator Name Example Result


+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
(Introduced in PHP 5.6)
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right
Assignment Same as... Description
x=y x=y
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result Show
it
== Equal $x == $y Returns true if $x is equal to $y Try it
»
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same Try it
type »
!= Not equal $x != $y Returns true if $x is not equal to $y Try it
»
<> Not equal $x <> $y Returns true if $x is not equal to $y Try it
VSR Govt Degree College,Movva

»
!== 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

.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1


PHP Array Operators
The PHP array operators are used to compare arrays.
Operator Name Example Result
+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y
***********************************************************************************
PHP Constants.
Constants are like variables except that once they are defined they cannot be changed or undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid
constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Where
 name: Specifies the name of the constant
 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
Constants are case sensitive in PHP
Constants are Global
Constants are automatically global and can be used across the entire script.
The example below uses a constant inside a function, even if it is defined outside the function:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() { echo GREETING;
}
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");

if ($t < "20") {


echo "Have a good day!";
}
?>
</body>
VSR Govt Degree College,Movva

</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

PHP while Loops


The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) { code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to run as long as $x
is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop runs ($x++):
<?php
$x = 1; while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and repeat the
loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and
then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the
loop will continue to run as long as $x is less than, or equal to 5:
<?php
$x = 1; do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This
means that the do while loop would execute its statements at least once, even if the condition is false the first
time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked:
<?php
$x = 6; do {
echo "The number is: $x <br>";
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

writeMsg(); // call the function


?>
Calling functions
Functions come in two flavors: those built in to the language and those you define yourself. PHP has hundreds of
built-in functions. Look at the following snippet for an example of a function in use:
strtoupper(“Hello Web!”);
A function call consists of the function name (strtoupper in this case) followed by parentheses. If you want to
pass information to the function, you place it between these parentheses. A piece of information passed to a
function in this way is called an argument. Some functions require that more than one argument be passed to
them, separated by commas:
some_function($an_argument, $another_argument);
<?php
function writeMsg() { echo "Hello world!";
}
writeMsg(); // call the function
?>
The function writeMsg() is called without any parameters, however you can also pass parameters to PHP
functions and you can also set default values to PHP functions.
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable. Arguments are
specified after the function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is called,
we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different
first names, but an equal last name:
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) { echo "$fname Refsnes.<br>";
}
familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim");
familyName("Borge");
?>
</body>
</html>
VSR Govt Degree College,Movva

Returning Values from User-Defined Functions


A function can return a value using the return statement in conjunction with a value. The return statement stops
the execution of the function and sends the value back to the calling code.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y; return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>"; echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
Variable Scope
A variable declared within a function remains local to that function. In other words, it is not available outside the
function or within other functions. In larger projects, this can save you from accidentally overwriting the
contents of a variable when you declare two variables with the same name in separate functions.
<?php Function_test()
{
$testvariable = “this is a test variable”;
}
echo “test variable: “.$testvariable.”<br/>”;
?>
Put these lines into a text file called scopetest.php and place
this file in your webserver document root. When you access
this script through your web browser, it should look like

Figure: Variable Scope: A Variable Declared Within a


Function Is Unavailable Outside the Function.
The value of the variable $testvariable is not printed because
no such variable exists outside the test() function.
Accessing Variables with the global Statement
From within one function, you cannot (by default) access a variable defined in another function or elsewhere in
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.

Fig: Accessing Global Variables with the global Statement


 You need to use the global statement within every function that needs to access a particular named
global variable.
 You can declare more than one variable at a time with the global statement by simply separating each
of the variables you want to access with commas:
global $var1, $var2, $var3
Saving State Between Function Calls with the static Statement
Local variables within functions have a short but happy life—they come into being when the function is called
and die when execution is finished, as they should. Occasionally, however, you might want to give a function a
rudimentary memory. Assume that you want a function to keep track of the number of times it has been called so
that numbered headings can be created by a script.
If you declare a variable within a function in conjunction with the static statement, the variable remains local to
the function, and the function “remembers” the value of the variable from execution to execution.
<?php
function numberedHeading($txt)
{
static $num_of_calls = 0;
$num_of_calls++;
echo “<h1>”.$num_of_calls.” “. $txt.”</h1>”;
}
numberedHeading(“Widgets”);
VSR Govt Degree College,Movva

echo “<p>We build a fine range of widgets.</p>”; numberedHeading(“Doodads”);


echo “<p>Finest in the world.</p>”;
?>
More About Arguments
Rather than just passing values as arguments to functions, PHP allows you to pass arguments as default values
and by references.
a) Setting Default Values for Arguments
PHP provides a nifty feature to help build flexible functions. Until now, you’ve heard that some functions
require one or more arguments. By making some arguments optional, you can render your functions a little less
autocratic.
<?php
function fontWrap($txt, $fontsize)
{
echo “<span style=\”font-size:$fontsize\”>”.$txt.”</span>”;
}
fontWrap(“A Heading<br/>”,”24pt”); fontWrap(“some body text<br/>”,”16pt”); fontWrap(“smaller body
text<br/>”,”12pt”); fontWrap(“even smaller body text<br/>”,”10pt”);
?>
In above program a useful little function that wraps a string in an HTML span element (at line 4).
To give the user of the function the chance to change the font-size style, you can demand a
$fontsize argument in addition to the string( at line 2). The above program generates the following output.
Passing Variable References to Functions
When you pass arguments to functions, they are stored as copies in parameter variables. Any changes made to
these variables in the body of the function are local to that function and are not reflected beyond it.
You can change this behavior by creating a reference to your original variable. You can think of a reference as a
signpost that points to a variable. In working with the reference, you are manipulating the value to which it
points. This can be implemented as
<?php
function addFive(&$num)
{
$num += 5;
}
$orignum = 10; addFive($orignum); echo $orignum;
?
When you pass an argument to a function by reference, as in line 7, the contents of the variable you pass
($orignum) are accessed by the argument variable and manipulated within the function, rather than just a copy of
VSR Govt Degree College,Movva

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

// Creating three objects of Books


$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Member Functions:
After creating our objects, we can call member functions related to that object. A member function typically
accesses members of current object only.
Example:
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$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>" ;
}
}

/* Creating New object using "new" operator */


$maths = new Books;

/* Setting title and prices for the object */


$maths->setTitle( "Algebra" );
$maths->setPrice( 7 );

/* Calling Member Functions */


$maths->getTitle();
$maths->getPrice();
?>
Constructors:
A constructor is a key concept in object oriented programming in PHP. Constructor in PHP is special type of
function of a class which is automatically executed as any object of that class is created or instantiated.
Constructor is also called magic function because in PHP, magic methods usually start with two underscore
characters.
Below is the sample code for the implementation of constructors:
Program for Constructors:
<?php
class GeeksforGeeks
{
public $Geek_name = "GeeksforGeeks";

// Constructor is being implemented.


public function __construct($Geek_name)
{
$this->Geek_name = $Geek_name;
}
VSR Govt Degree College,Movva

}
// 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

6. $str3='Using escape sequences \n in single quoted string';


7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape sequences and
variables will be interpreted using double quote PHP strings.
Example 1
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Output:
Hello text within double quote
Now, you can't use double quote directly inside double quoted string.
Example 2
1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>
Output:
Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on line 2
We can store multiple line text, special characters and escape sequences in a double quoted PHP string.
Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is provided after this
heredoc <<< operator, and immediately a new line is started to write any text. To close the quotation, the string
follows itself and then again that same identifier is provided. That closing identifier must begin from the new
line without any whitespace or tab.
Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters and underscores,
and must start with an underscore or a non-digit character.
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.

Investigating Strings with PHP


A string is a collection of characters. String is one of the data types supported by PHP.The string variables can
containalphanumeric characters. Strings are created when;
 You declare variable and assign string characters to it
 You can directly use them with echo statement.
 String are language construct, it helps capture words.
 Learning how strings work in PHP and how to manipulate them will make you a very effective and
productivedeveloper.
1.Finding the Length of a String with strlen()
You can use strlen() to determine the length of a string. strlen() requires a string and returns an integer
representing the number of characters in the variable you have passed it.
Example:
if (strlen($membership) == 4) { print "Thank you!";
} else {
print "Your membership number must have 4 digits<P>";
}
2. Finding a Substring Within a String with strstr()
You can use strstr() to test whether a string exists embedded within another string. strstr() requires two
arguments: a source string and the substring you want to find within it. The function returns false if the substring
is absent.
Otherwise, it returns the portion of the source string beginning with the substring.Example:
$membership = "pAB7";
if (strstr($membership, "AB")) {
print "Thank you. Don't forget that your membership expires soon!";
} else {print "Thank you!";}
VSR Govt Degree College,Movva

3. Finding the Position of a Substring with strpos()


The strpos() function tells you both whether a string exists within a larger string and where it is to be found.
strpos() requires two arguments: the source string and the substring you are seeking. The function also
accepts an optional third argument, an integer representing the index from which you want to start searching. If
the substring does not exist, strpos() returns false; otherwise, it returns the index at which the substring begins.
$membership = "mz00xyz";
if (strpos($membership, "mz") === 0) {print "hello mz";
}
4. Extracting Part of a String with substr()
The substr() function returns a portion of a string based on the start index and length of the portion you are
looking for. This function demands two arguments: a source string and the starting index. It returns all characters
from the starting index to the end of the string you are searching.
$test = "scallywag";
print substr($test,6); // prints "wag"print substr($test,6,2) // prints "wa"
5. Tokenizing a String with strtok()
You can parse a string word by word using strtok(). The strtok() function initially requires two arguments: the
string to be tokenized and the delimiters by which to split the string. The delimiter string can include as many
characters as you want, and the function will return the first token found. After strtok() has been called for the
first time, the source string will be cached. For subsequent calls, you should pass strtok() only the delimiter
string. The function will return the next found token every time it is called, returning false when the end of the
string is reached. strtok() will usually becalled repeatedly within a loop.
<html>
<head>
<title>Listing 13.3 Dividing a string into tokens with strtok()</title>
</head>
<body>
<?php
$test = "http://www.deja.com/qs.xp?";
$test .= "OP=dnquery.xp&ST=MS&DBS=2&QRY=developer+php";
$delims = "?&";
$word = strtok($test, $delims);while (is_string($word)) {
if ($word) {
print "$word<br>";
} $word = strtok($delims);
} ?>
</body> </html>
VSR Govt Degree College,Movva

Manipulating Strings with PHP


A PHP String is a sequence of characters i.e., used to store and manipulate text. PHP provides a rich set of
functions to manipulate string. The following are some of such functions.
a) Cleaning Up a String with trim(), ltrim(), rtrim(), and strip_tags()
The functions trim(), ltrim(), rtrim() are used to remove white spaces from a string. trim():- removes all spaces in
a string.
ltrim():- removes spaces at the beginning of stringrtrim():-removes spaces at the end of string
strip_tags():- used to escape(strip) without applying HTML and PHP tags to stringExample:
<?php
$str=”<b> PHP web development</b>”;
each trim($str); each ltrim($str); each rtrim($str);
each strip_tags ($str);
?>
b) Replacing a Portion of a String Using substr_replace()
The substr_replace() function works similarly to the substr() function, except it enables you to replace the
portion of the string that you extract. The function requires three arguments: the string to transform, the text to
add to it, and the starting index; it also accepts an optional length argument. The substr_replace() function finds
the portion of a string specified by the starting index and length arguments, replaces this portion with the string
provided, and returns the entire transformed string.
Example:
The following code fragment for renewing a user’s membership number changes its second two characters:
<?php
$membership = “mz11xyz”;
$membership = substr_replace($membership, “12”, 2, 2);echo “New membership number: $membership”;
// prints “New membership number: mz12xyz”
?>
Output:
New membership number: mz12xyz
c) Converting Case
 To get an uppercase version of a string, use the strtoupper () function.
 To convert a string to lowercase characters, use the strtolower () function.
 The ucwords () function makes the first letter of every word in a string uppercase
<?php
$membership = “mz11xyz”;
$membership = strtoupper ($membership);
VSR Govt Degree College,Movva

echo “$membership”; // prints “MZ11XYZ”


$membership1 = strtolower ($membership);
echo “$membership1”; // prints “mz11xyz”
$full_name = “violet elizabeth bott”;
$full_name = ucwords($full_name);
echo $full_name; // prints “Violet Elizabeth Bott”
?>
d) Wrapping Text with wordwrap () and nl2br ():
When you present plaintext within a web page, you are often faced with a problem in which new lines are not
displayed and your text runs together into one big mess. The nl2br() function conveniently converts every new
line into an HTML break. So
<?php
$string = “one line\n”;
$string .= “another line\n”;
$string .= “a third for luck\n”;
echo nl2br($string);
?>
Output:
one line<br /> another line<br />
a third for luck<br />
If you might want to add arbitrary line breaks to format a column of text. The wordwrap () function is perfect for
this.
<?php
$string = “Given a long line, wordwrap() is useful as a means of “;
$string .= “breaking it into a column and thereby making it easier to read”;
echo wordwrap($string);
?>
Output:
Given a long line, wordwrap() is useful as a means of breaking it into a column and thereby making it easier to
read
e) Breaking Strings into Arrays with explode ()
The explode () breaks up a string into an array, which you can then store, sort, or examine as you want. The
explode () function requires two arguments: the delimiter string that you want to use to break up the source
string and the sourcestring itself.
VSR Govt Degree College,Movva

Working with Date and Time Functions in PHP.


The date/time functions allow you to get the date and time from the server where your PHP script runs. You can
then use the date/time functions to format the date and time in several ways.
Time () : Returns the current time as a Unix timestamp.date () :- Formats a local date and time.
mktime() :- Returns the Unix timestamp for a date. Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo date("l") . "<br>";
echo date("l jS \of F Y h:i:s A") . "<br>";
echo "Oct 3,1975 was on a ".date("l", mktime(0,0,0,10,3,1975)) . "<br>"; echo date(DATE_RFC822) . "<br>";
echo date(DATE_ATOM,mktime(0,0,0,10,3,1975));
?>
</body>
</html>
Output:
Saturday
Saturday 12th of January 2019 11:53:38 PM
Oct 3,1975 was on a Friday
Sat, 12 Jan 19 23:53:38 -0500
1975-10-03T00:00:00-04:00
------XXXXX--------

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

<h1><?php print $message ?></h1> Guess number: <?php print $num_tries?>


<form action="<?php print $_SERVER[PHP_SELF] ?>" method="POST">Type your guess here:
<input type="text" name="guess" value="<?php print $guess?>">
<input type="hidden" name="num_tries" value="<?php print $num_tries?>">
</form>
</body>
</html>
Redirecting the user
Redirection is an integral part of modern website. If something happens on your website like a user submitted a
comment or logged in, he should be redirected to thank you page or user profile page respectively.
PHP provides a simple and clean way to redirect your visitors to another page that can be either relative or can
be cross domain.
Here is a simple redirection script that will redirect to thank you page if the comment is submitted
successfully. We will use the header('location: thankyou.html')function to redirect to the thank you page. The
location is the parameter along with the path to file in the header() function.
PHP code with HTML to redirect to another page:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$comment = $_POST['comment'];
$name = $_POST['name'];
if($comment && $name) {
header('location: thankyou.html');
}
}
?>
<form action="comment.php" method="POST">
<input type="text" name="Name">
<textarea name="comment"></textarea>
<input type="submit" value="submit">
</form>
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.

Setting a Cookie with PHP


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by
$_COOKIE superglobal variable.
1. setcookie("CookieName", "CookieValue");/* defining name and value only*/
2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60
seconds or 3600 s econds)
VSR Govt Degree College,Movva

3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);


Example:
<?php
setcookie("user", "Srinivas");
?>
<html>
<body>
<?php if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Delete Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past.Example:
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
Sessions in PHP.
Session is used to store and pass information from one page to another temporarily (until user close the website).
In case of cookie, the information is store in user computer but in case of session information is not stored on the
user’s computer.

A session is a way to store information (in variables) to be used across multiple pages.
VSR Govt Degree College,Movva

Why use session in PHP


When you work with any application, you open it, do some changes, and then you close it. This is much like a
Session. The computer knows who you are. It knows when you start the application and when you end. But on
the internet there is one problem; the web server does not know who you are or what you do, because the HTTP
address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username,
favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold
information about one single user, and are available to all pages in one application.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set
somesession variables:
<?php
// Start the session session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat"; echo "Session variables are set.";
?>
</body>
</html>
Working with session Variable
Next, we create another page called "demo_session2.php". From this page, we will access the session
information weset on the first page ("demo_session1.php").
<?php session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page echo "Favorite color is " . $_SESSION["favcolor"] .
VSR Govt Degree College,Movva

".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . ".";


?>
</body>
</html>
Destroying Sessions and Unsetting Variables
To remove all global session variables and destroy the session, use session_unset() and session_destroy().
<?php session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variablessession_unset();
// destroy the session session_destroy();
?>
</body>
</html>
Passing session IDs in the Query String.
There are two methods to propagate a session id:
 Cookies
 URL parameter
The session module supports both methods. Cookies are optimal, but because they are not always available, we
also provide an alternative way. The second method embeds the session id directly into URLs.
PHP is capable of transforming links transparently. If the run-time option session.use_trans_sid is enabled,
relativeURIs will be changed to contain the session id automatically.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an
appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string.
Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to another page using
SID.
<?php session_start();
if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
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

Numeric Data Types


MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a different
database system, these definitions will look familiar to you.
The following list shows the common numeric data types and their descriptions −
INT − A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -
2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a width
of up to 11 digits.
TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to
127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
SMALLINT − A small integer that can be signed or unsigned. If signed, the allowable range is from -32768 to
32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5 digits.
MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed, the allowable range is from
-8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a width of up to
9 digits.
BIGINT − A large integer that can be signed or unsigned. If signed, the allowable range is from -
9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615. You can specify a width of up to 20 digits.
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)

Sr.No. Parameter & Description

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 />');

$sql = "CREATE TABLE tutorials_tbl( ".


"tutorial_id INT NOT NULL AUTO_INCREMENT, ".
"tutorial_title VARCHAR(100) NOT NULL, ".
"tutorial_author VARCHAR(40) NOT NULL, ".
VSR Govt Degree College,Movva

"submission_date DATE, ".


"PRIMARY KEY ( tutorial_id )); ";
if ($mysqli->query($sql)) {
printf("Table tutorials_tbl created successfully.<br />");
}
if ($mysqli->errno) {
printf("Could not create table: %s<br />", $mysqli->error);
}

$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

THE MYSQL DELETE STATEMENT


The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
MySQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
MySQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
-----xxxxxx----
UNIT – V
INTERACTING WITH MYSQL USING PHP
MySQL versus MySQLi Functions
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.

Does not support prepared statements. MySQLi supports prepared statements.

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.

Extension directory: ext/mysql. Extension directory: ext/mysqli.

Other MySQLi Advantages


 MySQLi function mysqli_query() allows to enforce error prone queries and prevents bugs like SQL
injection.
 Using MySQLi data fetch, we can get buffered or unbuffered based on server resource size.
 MySQLi API allows executing multiple queries with single expression using multi_query() function.
CONNECTING TO MYSQL WITH PHP
Before we can access data in the MySQL database, we need to be able to connect to the server. The basic
syntax for a connection to MySQL is as follows:
$mysqli = mysqli_connect(“hostname”, “username”, “password”, “database”);
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, use the
VSR Govt Degree College,Movva

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

die("Connection failed: " . $conn->connect_error);


}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code Explanation:
First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The
next lineof code runs the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array
that wecan loop through. The while() loop loops through the result set and outputs the data from the id, firstname
and lastnamecolumns

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy