Level 4 Sod PHP Programming
Level 4 Sod PHP Programming
What is PHP?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code is executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
Scripting languages: help in automating various software apps, web pages in a browser
One needs to compile the programming languages to machine code so as to run them on the
hardware of an underlying OS (operating system). A user needs to deploy a certain Integrated
Development Environment (IDE) for using programming languages. A programmer needs to
provide an instruction set for the computers for achieving certain goals. One can also implement
certain algorithms by writing the programs
Parameters Scripting Language Programming Language
Language Type The scripting languages are The programming languages are
interpreter-based languages. compiler-based languages.
Compilation You don’t need to compile these These languages first need a compilation.
languages.
Design These make the coding process simple These provide full usage of the
and fast. languages.
File Type Scripting languages don’t create any Programming languages create .exe files.
file types.
Complexity These are very easy to use and easy to These are pretty complex in terms of
write. writing and usage.
Type of Coding Scripting languages help write a small Programming languages help write the
piece of an entire code. full code concerning a program.
Developing These take less time because they These take more time because a
Time involve lesser code. programmer must write the entire code.
Requirement of Scripting languages require hosts for Programming languages are self-
Host execution. executable. They don’t require any host.
Length of These involve very few and short These require numerous lines of coding
Codes coding lines. for a single function.
Support These provide limited support to data These provide rich support for graphic
types, user interface design, and design, data types, and user interface
graphic design. design.
Maintenance These involve very low maintenance. These involve high maintenance.
Example VB Script, Perl, Ruby, PHP, C, C++, COBOL, Basic, VB, C#, Pascal,
JavaScript, etc. Java, etc.
PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
A compiler translates the entire source code into machine code before execution, resulting in
faster execution since no translation is needed during runtime.
An interpreter is a software tool that directly executes high-level programming code without
prior translation into machine code. It reads and executes the code line by line, translating each
line into machine instructions on the fly, making it easier to identify errors and debug the code.
1.2: Describe PHP Syntax, Data types, Variables, Operators and Arrays.
Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
EXAMPLE:
$x = 5;
$y = "John"
Wth PHP, there are two basic ways to get output: echo and print.
In this tutorial we use echo or print in almost every example. So, this chapter contains a little
more info about those two output statements.
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
Display Text
The following example shows how to output text with the echo command (notice that the text
can contain HTML markup):
Example
echo "<h2>PHP is Fun!</h2>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
Display Variables
The following example shows how to output text and variables with the echo statement:
Example
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo $x + $y;
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
1. resource
2. NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Rules for integer:
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers
with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:
Example:<?php
1. $company = "Javatpoint";
2. //both single and double quote statements will treat different
3. echo "Hello $company";
4. echo "</br>";
5. echo 'Hello $company';
6. ?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Null is a special data type that has only one value: NULL. There is a convention of writing it in
capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
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.
x=y x=y The left operand gets set to the value of the expression
on the right
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
The PHP comparison operators are used to compare two values (number or string):
PHP has two operators that are specially designed for strings.
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
/* This is a
multi-line comment */
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
if
if-else
if-else-if
nested if
PHP If Statement
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
1. if(condition){
2. //code to be executed
3. }
Flowchart
Example
1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
Output:
PHP if-else statement is executed whether condition is true or false. If-else statement is slightly
different from if statement. It executes one block of code if the specified condition is true and
another block of code if the condition is false.
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Example
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Output:
12 is even number
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can
check multiple conditions using this statement.
Syntax
1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }
Flowchart
Example
1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
Output:
B Grade
PHP nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax
1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }
Flowchart
Example
1. <?php
2. $age = 23;
3. $nationality = "Indian";
4. //applying conditions on nationality and age
5. if ($nationality == "Indian")
6. {
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>
SWITCH
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default must always be
the last statement.
2. There can be only one default in a switch statement. More than one default may lead to
a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the statements
will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch
expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
PHP Switch Flowchart
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for
loop is used when you already know how many times you want to execute a block of code.
Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is
false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
PHP While Loop
PHP while loop can be used to traverse set of code like for loop. The while loop executes a block
of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from
the body of loop.
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you have
to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the
code.
The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas
do-while loop checks the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
The while loop is also named as entry control The do-while loop is also named as exit control loop.
loop.
The body of the loop does not execute if the The body of the loop executes at least once, even if the
condition is false. condition is false.
Condition checks first, and then block of Block of statements executes first and then condition
statements executes. checks.
This loop does not use a semicolon to Do-while loop use semicolon to terminate the loop.
terminate the loop.
Function Description
max() It is used to return the highest value in an array, or the highest value of several
specified values.
min() It returns the lowest value in an array, or the lowest value of several specified
values.
getrandmax() It is used to return the maximum value by using rand().
fmod() It is used to return the floating point remainder of the division of the argument.
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>
Output:
my name is khan
2) PHP strtoupper() function
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>
Output:
MY NAME IS KHAN
3) PHP ucfirst() function
The ucfirst() function returns string converting first character into uppercase. It doesn't change
the case of other characters.
Syntax
Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>
Output:
My name is KHAN
4) PHP lcfirst() function
The lcfirst() function returns string converting first character into lowercase. It doesn't change the
case of other characters.
Syntax
Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:
mY name IS KHAN
5) PHP ucwords() function
The ucwords() function returns string converting first character of each word into uppercase.
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>
Output:
24
Example
php
<?php
function add($a, $b) {
return $a + $b;
}
Example
php
<?php
function greet($name = "Guest") {
return "Hello, " . $name . "!";
}
Create File
To create a new file, you can use the fopen() function with the w or w+ mode. If the file does not
exist, it will be created.
<?php
$filename = 'example.txt';
$file = fopen($filename, 'w'); // Open file for writing
if ($file) {
echo "File '$filename' created successfully.";
fclose($file);
} else {
echo "Error creating file '$filename'.";
}
?>
Append Data to File
To append data to an existing file, use the fopen() function with the a mode and then write data
using the fwrite() function.
<?php
$filename = 'example.txt';
$file = fopen($filename, 'a'); // Open file for appending
if ($file) {
$data = "Appending this data to the file.\n";
fwrite($file, $data);
echo "Data appended to file '$filename'.";
fclose($file);
} else {
echo "Error opening file '$filename' for appending.";
}
?>
Read File
To read the contents of a file, use the fread() function after opening the file with the fopen()
function in r mode. Alternatively, you can use file_get_contents() for simplicity.
php
<?php
$filename = 'example.txt';
$file = fopen($filename, 'r'); // Open file for reading
if ($file) {
$contents = fread($file, filesize($filename));
echo "File contents:\n$contents";
fclose($file);
} else {
echo "Error opening file '$filename' for reading.";
}
// Using file_get_contents()
$contents = file_get_contents($filename);
echo "File contents:\n$contents";
?>
Write File
To write data to a file, use the fopen() function with the w mode and then write data using the
fwrite() function. This will overwrite the existing content.
php
<?php
$filename = 'example.txt';
$file = fopen($filename, 'w'); // Open file for writing
if ($file) {
$data = "Writing new data to the file.\n";
fwrite($file, $data);
echo "Data written to file '$filename'.";
fclose($file);
} else {
echo "Error opening file '$filename' for writing.";
}
?>
Rename File
To rename a file, use the rename() function.
php
<?php
$oldName = 'example.txt';
$newName = 'new_example.txt';
if (rename($oldName, $newName)) {
echo "File renamed from '$oldName' to '$newName'.";
} else {
echo "Error renaming file '$oldName'.";
}
?>
ZIP File
To create a ZIP file and add files to it, use the ZipArchive class.
php
<?php
$zip = new ZipArchive();
$filename = "example.zip";
PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if
connection is established or null.
Syntax
1. resource mysqli_connect (server, username, password)
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax
mysqli_close() ;
MYSQLi CREATE DB
Example
1. <?php
2. $host = 'localhost';
3. $user = ' ';
4. $pass = ' ';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>
Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NU
LL, emp_salary INT NOT NULL,primary key (id))";
14. if(mysqli_query($conn, $sql)){
15. echo "Table emp5 created successfully";
16. }else{
17. echo "Could not create table: ". mysqli_error($conn);
18. }
19. mysqli_close($conn);
20. ?>
Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
14. if(mysqli_query($conn, $sql)){
15. echo "Record inserted successfully";
16. }else{
17. echo "Could not insert record: ". mysqli_error($conn);
18. }
19.
20. mysqli_close($conn);
21. ?>
Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $name="Rahul";
15. $salary=80000;
16. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
17. if(mysqli_query($conn, $sql)){
18. echo "Record updated successfully";
19. }else{
20. echo "Could not update record: ". mysqli_error($conn);
21. }
22.
23. mysqli_close($conn);
24. ?>
Example
1. <?php
2. $host = 'localhost';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $sql = "delete from emp4 where id=$id";
15. if(mysqli_query($conn, $sql)){
16. echo "Record deleted successfully";
17. }else{
18. echo "Could not deleted record: ". mysqli_error($conn);
19. }
20. mysqli_close($conn);
21. ?>
MySQL INSERT statement is used to store or add data in MySQL table within the database. We
can perform insertion of records in two ways using a single query in MySQL:
1. Insert record in a single row
2. Insert record in multiple rows
Example
22. <?php
23. $host = 'localhost';
24. $user = ' ';
25. $pass = ' ';
26. $dbname = 'test';
27.
28. $conn = mysqli_connect($host, $user, $pass,$dbname);
29. if(!$conn){
30. die('Could not connect: '.mysqli_connect_error());
31. }
32. echo 'Connected successfully<br/>';
33.
34. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
35. if(mysqli_query($conn, $sql)){
36. echo "Record inserted successfully";
37. }else{
38. echo "Could not insert record: ". mysqli_error($conn);
39. }
40.
41. mysqli_close($conn);
42. ?>
PHP MYSQLI UPDATE
MySQL UPDATE query is a DML statement used to modify the data of the MySQL table within
the database. In a real-life scenario, records are changed over a period of time. So, we need to
make changes in the values of the tables also. To do so, it is required to use the UPDATE query.
The UPDATE statement is used with the SET and WHERE clauses. The SET clause is used to
change the values of the specified column. We can update single or multiple columns at a time.
PHP MySQLi Update Record Example
Example
25. <?php
26. $host = 'localhost';
27. $user = ' ';
28. $pass = ' ';
29. $dbname = 'test';
30.
31. $conn = mysqli_connect($host, $user, $pass,$dbname);
32. if(!$conn){
33. die('Could not connect: '.mysqli_connect_error());
34. }
35. echo 'Connected successfully<br/>';
36.
37. $id=2;
38. $name="Rahul";
39. $salary=80000;
40. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
41. if(mysqli_query($conn, $sql)){
42. echo "Record updated successfully";
43. }else{
44. echo "Could not update record: ". mysqli_error($conn);
45. }
46.
47. mysqli_close($conn);
48. ?>
MySQL DELETE statement is used to remove records from the MySQL table that is no longer
required in the database. This query in MySQL deletes a full row from the table and
produces the count of deleted rows. It also allows us to delete more than one record from the
table within a single query, which is beneficial while removing large numbers of records from a
table. By using the delete statement, we can also remove data based on conditions.
PHP MySQLi Delete Record Example
Example
22. <?php
23. $host = 'localhost';
24. $user = ' ';
25. $pass = ' ';
26. $dbname = 'test';
27.
28. $conn = mysqli_connect($host, $user, $pass,$dbname);
29. if(!$conn){
30. die('Could not connect: '.mysqli_connect_error());
31. }
32. echo 'Connected successfully<br/>';
33.
34. $id=2;
35. $sql = "delete from emp4 where id=$id";
36. if(mysqli_query($conn, $sql)){
37. echo "Record deleted successfully";
38. }else{
39. echo "Could not deleted record: ". mysqli_error($conn);
40. }
41. mysqli_close($conn);
42. ?>
PHP MYSQLSELECT
The SELECT statement in MySQL is used to fetch data from one or more tables. We can
retrieve records of all fields or specified fields that match specified criteria using this statement.
Example
27. <?php
28. $host = 'localhost';
29. $user = ' ';
30. $pass = ' ';
31. $dbname = 'test';
32. $conn = mysqli_connect($host, $user, $pass,$dbname);
33. if(!$conn){
34. die('Could not connect: '.mysqli_connect_error());
35. }
36. echo 'Connected successfully<br/>';
37.
38. $sql = 'SELECT * FROM emp4';
39. $retval=mysqli_query($conn, $sql);
40.
41. if(mysqli_num_rows($retval) > 0){
42. while($row = mysqli_fetch_assoc($retval)){
43. echo "EMP ID :{$row['id']} <br> ".
44. "EMP NAME : {$row['name']} <br> ".
45. "EMP SALARY : {$row['salary']} <br> ".
46. "--------------------------------<br>";
47. } //end of while
48. }else{
49. echo "0 results";
50. }
51. mysqli_close($conn);
52. ?>