UT-I PHP & Mysql
UT-I PHP & Mysql
MYSQL
V Semester
M NAGA V VARA PRASAD, Assistant Professor, CS, BVRC (III Chem)
Introduction to PHP:
PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages.
• PHP is an acronym for “PHP: Hypertext Pre-processor”.
• PHP was created by Rasmus Lerdorf in 1994.
• PHP is a widely-used, open source scripting language.
• PHP scripts are executed on the server.
• PHP is free to download and use.
Uses of PHP
• 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
• You can output HTML, images, PDF files, and even flash movies.
• You can also output any text, such as XHTML and XML.
• 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 Features:
⮚ Performance: Script written in PHP executes much faster then those scripts written in other languages such as JSP & ASP.
⮚ Open Source Software: PHP source code is free available on the web, you can developed all the version of PHP according to
your requirement without paying any cost.
⮚ Platform Independent: PHP is called platform independent because a PHP program can run on different kinds of platform
like Window os, Linux os etc
⮚ Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.
⮚ Object Oriented: PHP also supports object oriented programming structure.
⮚ Interpreted: It uses interpreter and doesn’t require any compiler.
⮚ Embedded: PHP code can be easily embedded within HTML tags and script.
⮚ Security: PHP is a secure language with encrypted technology. It prevent threads and virus attacks.
⮚ Database Connectivity: PHP supports all the leading databases such as MYSQL, SQLite, ODBC, etc.
Applications of PHP:
⮚ Web Development: PHP is widely used for creating dynamic websites and web applications by generating interactive content,
handling user inputs, and interacting with databases.
⮚ Command-Line Scripting: PHP can be used to write command-line scripts for automating repetitive tasks, such as data
processing or system monitoring.
⮚ Game Development: PHP is used for backend logic in browser-based multiplayer games, handling user authentication, scores,
and game state.
⮚ Real-Time Applications: PHP supports real-time applications like chat systems and live updates, typically using AJAX or
Web Sockets.
⮚ File Management: PHP handles file uploads and creates file management systems for organizing and downloading files
PHP File
⮚ PHP Files can contain text, HTML, CSS, JavaScript and PHP code
⮚ PHP code is executed on the server, and the result is sent back to the browser.
⮚ PHP Files have extension “ .php”
PHP Syntax:
A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with?>
<?php
?>
The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting
code. PHP statements end with a semicolon (;). 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:
Example of PHP:
<!DOCTYPE html>
<html>
<body>
<h1>My First PHP Page</h1>
< ?php
// Use echo to print on console
echo “Hello World!”;
?>
</body>
</html>
A comment in PHP code is a line that is not executed as a part of the program. These are non-executable statements.
Types:
Variable:
Variables are used to store the data values(like int, float, char, etc…). Php is a dynamically typed language. i.e., Php has no data
type declaration.
The value can be assigned to the variable in following manner.
Syntax: $variable_name=value;
Eg: <?php
//Declaring variables
$txt=“Hello World!”;
$number=10;
//Displaying variable values
echo $txt;
echo $number;
?>
• All variables in php start with a $(dollar) 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 in PHP can only contain alpha-numeric characters and underscores( A-z, 0-9, and_ ).
• A variable name cannot contain spaces.
PHP Constants:
Data types in php define the values of variable can hold to store information.
PHP data types are used to hold the different types of data or values.
Php supports 8 primitive data types that can be categorized further in 3 types.
1. Scalar Types/predefined
2. Compound Types/user-defined
3. Special Types.
1. Scalar Types/predefined
It holds only single value. There are 4 scalar data types in PHP.
a. Integer b. Float c. String d. Boolean
?>
Output: 123
b. Float (or) double: A Floating point number is a number with a decimal point. It can hold decimal point.
0.12, 0.23 etc…
Eg: <?php
$a=1.234;
echo "a=",$a;
?>
Output: a=1.234
c. String: A string is a non-numeric data type. It holds letters, numbers and even special characters.
“Hello World!”
• String values must be either within single quotes (or) in double quotes.
• Integer can be decimal (base 10), octal (base 8), Hexadecimal (base 16).
• The range of an integer must be lie between 2147483648 – 2147483647 .
Eg: <?php
$x= "Helloworld!";
$y= 'Helloworld!';
echo $x;
echo "\n";
echo $y;
?>
Output: Helloworld! Helloworld!
d. Boolean: Booleans are the simplest data type works like switch. It holds only two values i.e., True (1) or False (0)
It is used with conditional statements, if the condition is correct it returns True, otherwise False.
Eg: <?php
// Assign the value TRUE to a variable
$b = true;
echo $b;
?> Output: 1
2. Compound Types/user-defined
It can hold multiple values. There are 2 compound data types in php.
a. array
b. object
a. array: It can store multiple values of same data type in a single variable.
It is useful to aggregate a series of related items.
Eg: <?php
$fruits = array("Apple", "Banana", "Mango");
echo $fruits[0]; // Output: Apple
echo “\n”;
echo $fruits[1]; // Output: Banana
?>
b. object: objects are the instances of user-defined classes that can store both data(properties) and actions(methods).
Eg: <?php // Create an object from class
class Student { $stud1 = new Student();
// Property
public $name; // Set the property
echo $stud1->name = "Rahul";
// Method echo “\n”;
function sayHello() {
echo "Hello, I am a student."; // Use the method
} $stud1->sayHello();
} ?>
Output: Hello, I am a student.
3. Special Types
The assignment operators are used to assign values to variables. Eg: Program
<?php
$x = 10;
echo "$x \n"; // Outputs: 10
$x = 20;
$x += 30;
echo "$x \n"; // Outputs: 50
$x = 50;
$x -= 20;
echo "$x \n"; // Outputs: 30
$x = 5;
$x *= 25;
echo "$x \n"; // Outputs: 125
$x = 50;
$x /= 10;
echo "$x \n"; // Outputs: 5
$x = 100;
$x %= 15;
echo "$x\n"; // Outputs: 10
?>
3. Comparison operators
The comparison operators are used to compare two values in Eg: Program
a Boolean fashion. <?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
Output: bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
4. Incrementing and Decrementing Operators: Eg: Program
Eg: Program
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0)))
{
echo "$year is a leap year.";
}
else
{
echo "$year is not a leap year.";
}
?>
Output: 2014 is not a leap year.
6. String Operators:
There are two operators which are specifically designed for strings.
Eg: Program
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
Output: Hello.world!
Hello world!
7. Array Operators:
Eg: Program
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
Flow Control Functions in PHP:
if statement:
(if) is used to test a condition, if the condition is true, the statements inside if will be executed.
Syntax: if (condition)
Eg: Program
{
<?php
Statements;
$age=20;
}
if ($age>18)
Statement-n;
{
echo “You are eligible for vote”;
Flow Chart:
}
?>
If the condition is true statements inside, the if block will be executed otherwise else block will be executed.
Syntax: if(condition)
{ Eg: Program
Statement block 1; <?php
} $age=17;
else if ($age>18)
{ {
Statement block2; echo “You are eligible for vote”;
} }
Statement-n else
{
echo “You are not eligible for vote”
Flow Chart:
}
?>
When a series of decisions are involved, we may have to use more than one if statements in nested as follows.
Syntax:
Flow Chart:
if (condition1)
{
// Code to execute if condition1 is true
}
elseif (condition2)
{
// Code to execute if condition2 is true
}
elseif (condition3)
{
// Code to execute if condition3 is true
}
lse
{
// Code to execute if none of the above
conditions are true
}
Eg: Program
<?php
$score = 92;
if ($score >= 90)
{
echo "Excellent!";
}
elseif ($score >= 80)
{
echo "Good job!";
}
elseif ($score >= 70)
{
echo "You passed.";
}
else
{
echo "Sorry, you did not pass.";
}
?>
Output: Excellent!
switch...case statement :
Php provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an
expression against a list of integer or character constants. When a match is found, the statements associated with that constant
are executed. Flow Chart:
Syntax:switch(expression)
{
case value1: block-1 break;
case value2: block-2 break;
.........
...........
default: default-block break;
}
Statement-x;
Eg: Program
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?> Output: Today is Sunday. Do some rest.
PHP Loops:
The process of repeatedly executing a block of statements is known as looping. The statements in the block may be executed
any number of times, from zero to infinite number of times. If a loop continues forever, it is called an infinite loop.
• while Loop
• do...while Loop Eg: Program
• for Loop
<?php
• foreach Loop
$i = 1;
while($i <= 3)
while Loop: {
The while is an entry-controlled loop statement. $i++;
The test condition is evaluated and if the condition is true, then echo "The number is " . $i . "<br>";
the body of the loop is executed. After execution of the body, }
the test condition is once again evaluated and if it is true, ?>
the body is executed once again. This process is repeated until
the test condition returns a false value. Output: The number is 2
Syntax: Initialization; The number is 3
while (test condition)
{
// Code to be executed
//Increment/Decrement
}
Flow Chart:
do...while Loop
do … while loops through a block of code once, and then repeats the loop as along as the specific condition is true.
Syntax: Initialization;
Eg: Program
do
<?php
{
$i = 1;
// Code to be executed
do
//Increment/Decrement
{
$i++;
}while(condition);
echo "The number is " . $i . "<br>";
} while($i <= 5)
Flow Chart:
?>
Browser Output
Browser output is what you see on the screen when you open a .php file in a web browser.
PHP code runs on the server, and it sends the result (like HTML or text) to the browser.
Working with Functions
Function in PHP
• A function is a self-contained block of code that performs specific task.
• A large program can be divided into simple blocks functions.
• The main use of functions is code reusability.
• Function code written once can be called any number of times.
TYPES OF FUNCTIONS:
1) PREDEFINED FUNCTIONS: These functions that are prewritten and pretested in the library.
Example: array( ), print( ), var_dump( ), date( ), time( ), etc...
2) USER DEFINED FUNCTIONS: functions which are defined by the users are known as user defined functions.
Syntax: FUNCTION_NAME(parameters);
• PHP provides the option to pass parameters inside a function.
•You can pass as many as parameters your like.
Eg : Program 1
•These parameters work like variables inside your function.
<?php
•Values passed to function are actual arguments.
// Defining function
•Parameters in function definition are formal arguments.
function message( )
{
Eg : Program 2
echo "stay home stay safe";
<?php
}
// Defining function
function getSum($num1, $num2)
// Calling function
{
message( );
?> $sum = $num1 + $num2;
Output: stay home stay safe echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20);
?>
Output: Sum of the two numbers $num1 and $num2 is : 30
Returning the values from User- Defined Functions:
A function may or may not return a value. If it returns, it returns only one value.
The return statement is used to return a value to the calling function.
Syntax: return(expression);
Eg : Program 1
<?php
// Defining function
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}
Eg : Program 1
<?php
$greet = “Hello World!”;
// Defining function
function test( )
{
global $greet;
echo “greet \n”;
}
Static keyword is also used to declare variables in a function, which keep their value after the function has ended.
(or)
Static variables are similar to local variables but after executing the function, the value stored in the variable, remains as tease
till the end of the program
Eg : Program
<?php
// Defining function
function test( )
{
static $x=5;
$y=2;
$x++;
$y++;
echo $x;
echo $y;
}
test( );
test( );
?>
Output: 6
3
7
3
Arguments in functions:
Arguments in functions are the values or variables passed to a Calling function when it is call. These values are used by the
function definition to perform operations or return results.
Eg : Program Parameters
<?php
function sayHello($name)
{
echo "Hello, $name!";
}
sayHello(“Ravi!"); // Output: Hello, Ravi!
sayHello("Suresh!"); // Output: Hello, Suresh!
?>
Output:
Ravi
Suresh Arguments
Types of function arguments:
5) Positional arguments: When you call a function, the values you pass to it are called arguments.
The position(order) of each value must match the position of the parameters in the function.
Number of parameters must be equal to number of arguments.
Eg:
<?php
function greet($name, $age) {
echo "Hi, I am $name. I am $age years old.";
}
greet(“Ravi", 20);
?>
Output:
Hi, I am Ravi. I am 20 years old.
2) Keyword arguments: Keyword arguments (also called named arguments) let you specify the name of each argument when
calling a function.
a) Clear and easy to read,
b) Flexible (you can change the order),
c) Easier to work with when there are many parameters.
Eg:1
<?php
function introduce($name, $age, $city) {
echo "My name is $name, I am $age years old, and I live in $city.";
}
// Keyword arguments
introduce(age: 25, name: "Ravi", city: "Hyderabad");
?>
Output:
My name is Ravi, I am 25 years old, and I live in Hyderabad.
Eg:2
Mixing Positional and Keyword Arguments.
You can mix them, but keyword arguments must come after positional:
introduce("Ravi", age: 25, city: "Hyderabad"); // ✅ OK
introduce(name: "Ravi", 25, "Hyderabad"); // ❌ Error!
3) Default arguments: If you don’t give a value, PHP will automatically use the default value.
It makes the function optional to pass some values.
Syntax:
function functionName($param1 = default_value) {
// code
}
Eg:1
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}