0% found this document useful (0 votes)
7 views

PHP - REFERENCE

PHP is a server-side scripting language used for managing dynamic web pages and databases, first released in 1995. It supports various operations such as handling forms, database interactions, and encryption, and includes built-in functions for modular programming. The document also covers PHP syntax, data types, operators, conditional and iterative statements, and integration with MySQL for CRUD operations.
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)
7 views

PHP - REFERENCE

PHP is a server-side scripting language used for managing dynamic web pages and databases, first released in 1995. It supports various operations such as handling forms, database interactions, and encryption, and includes built-in functions for modular programming. The document also covers PHP syntax, data types, operators, conditional and iterative statements, and integration with MySQL for CRUD operations.
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/ 82

PHP - REFERENCE

PHP Overview

PHP is a server-side scripting language,


which is used to manage dynamic web
pages, databases and build websites with
features like session tracking and e-
commerce. On a day of 1995, Rasmus
Lerdorf unleashed the first version of
“Hypertext Preprocessor” also known as
the PHP language. It is also integrated
with several popular databases like
MySQL, PostgreSQL, Microsoft SQL
Server, Oracle etc.
Uses of PHP

1. Handling Forms: PHP can handle form operations. It can gather data, save
data to a file and send data through emails.
2. Database Operations: PHP can also create, read, update and delete
elements in your database.
3. Encryption: It can perform advanced encryption and encrypt data for you.
4. Dynamic Page Content: It can generate dynamic page content.
Basic Syntax PHP
PHP comments
Single line Comments

Multiline comment
Variables in PHP
Variables are containers that can store information which can be manipulated
or referenced later by the programmer within the code.

All variables should be denoted with a Dollar Sign ($)


Variables are assigned with the = operator, with the variable on the left-
hand side and the expression to be evaluated on the right.
Variable names can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ ).
Variables must start with a letter or the underscore “_” character.
Variables are case sensitive
Variable names cannot start with a number.
<?php
$txt = "Hello world!"; # Type String
$x = 5; # Type int
$y = 10.5; # Type Float

echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
How to Run PHP file?
To run PHP file we want a server here we are using WAMP

In the following path you can create a folder and store all the PHP files in it:
C:\wamp64\www
In the WAMP localhost it will show the folder

Just click the specific php file


PHP DataTypes

Data type specifies the type of value a variable requires to do various


operations without causing an error. By default, PHP provides the following
built-in data types:

String
Integer
Float
Boolean
Array
NULL
1.String
A string is a sequence of characters that holds letters and numbers. It can
be anything written inside single or double quotes.
For Example:
2. Integer
An integer is a non-decimal number typically ranging between -2,147,483,648
and 2,147,483,647.
3. Float
A float is a number with a decimal point. It can be an exponential number or
a fraction.
4. Boolean
A Boolean represents two values: True or False.
5. Array
Array is a collection of similar data elements stored in a single variable.
6. NULL
Null is a special data type with only one value which is NULL. In PHP, if a
variable is created without passing a value, it will automatically assign itself a
value of NULL.
PHP Operators
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. PHP Increment/ Decrement Operators
5. PHP Logical Operators
6. PHP String Operators
7. PHP Array Operators
8. PHP Conditional Operators
PHP Conditional Statements
PHP Conditional Statements
Conditional Statements are used to perform actions based on different
conditions. Sometimes when we write a program, we want to perform some
different actions for different actions. We can solve this by using conditional
statements.
In PHP we have these conditional statements:
1. if Statement.
2. if-else Statement
3. If-elseif-else Statement
4. Switch statement
1. if Statement
This statement executes the block of code inside the if statement if the expression
is evaluated as True.
2. if-else Statement
This statement executes the block of code inside the if statement if the
expression is evaluated as True and executes the block of code inside the else
statement if the expression is evaluated as False.
If-else-if-else
This statement executes different expressions for more than two conditions.
4. Switch Statement
This statement allows us to execute different blocks of code based on
different conditions. Rather than using if-elseif-if, we can use the switch
statement to make our program.
PHP Iterative Statements
PHP Iterative Statements
Iterative statements are used to run same block of code over and over again
for a certain number of times.
In PHP, we have the following loops:
1. while Loop
2. do-while Loop
3. for Loop
4. foreach loop
1. While Loop
The While loop in PHP is used when we need to execute a block of code again
and again based on a given condition. If the condition never becomes false,
the while loop keeps getting executed. Such a loop is known as an infinite
loop.
2. Do-While Loop
The do-while loop is similar to a while loop except that it is guaranteed to
execute at least once. After executing a part of a program for once, the rest of
the code gets executed based on a given boolean condition.
3. For Loop
The for loop is used to iterate a block of code multiple times.
4. Foreach loop
The foreach loop in PHP can be used to access the array indexes in PHP. It
only works on arrays and objects.
Function Basics
Function arguments are variables of some supported data type that are
processed within the body of the function. It can take input as an argument
and return value.
PHP has more than 1000 built-in functions, and in addition, you can also
create your own functions.

Advantages:
1. Functions reduce the complexity of a program and give it a modular
structure.
2. A function can be defined only once and called many times.
3. It saves a lot of code writing because you don't need to write the same
logic multiple times, you can write the logic once and reuse it.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.
Please check out our PHP reference for a complete overview of the PHP built-
in functions.
User Defined Functions: Apart from built-in functions, We can also create our
own functions and call them easily.
A user-defined function looks something like this:

<?php
Function functionname(){
//Code
}
functionname(); // Calling Function
?>
Function Arguments

Function Arguments: Argument is just like a variable which can be used to pass
through information to functions.
PHP supports Call by Value, Call by Reference, Default Argument Values and
Variable-length argument.
1. Call by Value
In Call by Value, the value of a variable is passed directly. This means if the value
of a variable within the function is changed, it does not get changed outside of
the function.
2. Call by Reference
In call by reference, the address of a variable (their memory location) is
passed. In the case of call by reference, we prepend an ampersand (&) to
the argument name in the function definition. Any change in variable
value within a function can reflect the change in the original value of a
variable.
3. Default Argument Values
If we call a function without arguments, then PHP function takes the default
value as an argument.
4. Variable Length Argument
It is used when we need to pass n number of arguments in a function. To use
this, we need to write three dots inside the parenthesis before the argument.
Arrays
An array is a collection of data items of the same data type. And
it is also known as a subscript variable.
1. Numeric Array
These are arrays with a numeric index where values are stored and accessed
in a linear fashion.
2. Associative Array
These are arrays with string as an index where it stores element values
associated with key values
3. Multidimensional Arrays
A multidimensional Array is an array containing one or more arrays where
values are accessed using multiple indices.
PHP-MySQl
What is MYSQL?
MySQL is a Database Management System.

What is a Database Management System?


The software system that enables users to define, create, maintain and
control access to the database is called a Database Management System. It is
a software for storing and retrieving users' data while considering appropriate
security measures.
Examples of DBMS include MySQL, PostgreSQL, Microsoft SQL Server, Oracle
Database, and Microsoft Access.+

In this Tutorial We will using PHP MyAdmin to use MySQl


Creating a Database and a table using PHP Myadmin
left click the WAMP icon and select PHP myadmin

enter root in the username field and keep


the password field empty and click Login
button
Enter the database name in the empty field in the
Databases tab and click the create button
Then it will open a tab where you can
enter the name for a table and enter
the number of rows and hit create
button

Enter the colum


detailsfor the table
and click Save
button
Connecting to MySQl
Inserting Data in MySQL

you can check if the rows


are entered in the
browse tab in
phpmyadmin
Selecting Data in MySQL
Updating Data in MySQL
Deleting Data in MySQL
CRUD Example
Now we will be integrating all of the previous PHP-MySQl programs into a
single and better one Here we will be using the same table and database, In
your case you can change them if you want!
index.html
<html>
<head>
<title>CRUD | Registration</title>
</head>
<body>
<form action="process.php" method="post">
Student ID: <input type="text" name="id"><br>
Student Name: <input type="text" name="name"><br>
Marks: <input type="text" name="mrk"><br>
Here we have four submit
<input type="submit" value="insert" name="insert">
<input type="submit" value="delete" name="delete"> buttons so that we can
<input type="submit" value="update" name="update"> select any button and it
<input type="submit" value="select" name="select"> will perform a specific task
</form>
</body>
</html>
process.php
this page and next few pages will
<?php
be on the process.php and their
if (isset($_POST['insert'])) {
explanation
dataEnter();
} In this page the code is generated with
if (isset($_POST['delete'])) { four functions which is being called when
dataDelete(); the specific button is clicked.
} This feature is done using
if (isset($_POST['update'])) { isset($_POST['button_name']) that checks
dataUpdate(); if the right button is being clicked or not.
} the button name is the one which we give
if (isset($_POST['select'])) { the submit button with name attribute in
dataSelect(); html form. please refer the previous page.
}
function dataEnter(){
$id = $_POST["id"]; This is the function for
$name = $_POST["name"]; inserting data into the mysql
$mark = $_POST["mrk"]; table.
$conn = new mysqli("localhost", "root", "", "mydb"); here i have directly entered
if ($conn->connect_error) { the details for connection
die("Connection failed: " . $conn->connect_error);
variable but you can also
}
seperate them using another
$sql = "INSERT INTO student (id, name, marks)
variables like for example:
VALUES ('$id', '$name', '$mark')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"; $servername = "localhost";
} else { $username = "root";
echo "Error: " . $sql . "<br>" . $conn->error; $password = "";
} $dbname = "mydb";
$conn->close();
}
function dataDelete() {
$name = $_POST["name"];
$conn = new mysqli("localhost", "root", "", "mydb");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM student WHERE name='$name'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
This is the function for deleting
} else {
the data for this we only want
echo "Error deleting record: " . $conn->error;
to enter the name of the
}
student details since it is only
$conn->close();
accepting the student name in
}
the code.
function dataUpdate() This is the code for
{ updating the data in the
$id = $_POST["id"]; table. Here we have to
$name = $_POST["name"]; enter both id and updated
$conn = new mysqli("localhost", "root", "", "mydb"); name in the html form
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE student SET name='$name' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
function dataSelect() {
$conn = new mysqli("localhost", "root", "", "mydb");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, marks FROM student";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["name"] . " " . $row["marks"] . "<br>";
}
} else {
This code fetches all the data
echo "0 results";
currently in the table and displays
}
it in the browser
$conn->close();
}
Output

click the back button on the


browser to move back to the
html form
When the select button is clicked

When the delete button is clicked


When the update button
is clicked
PHP Session Tracking
PHP Cookies
Cookie is a small file that the server embeds on the user's computer. Each
time the computer opens a webpage, the server will send a cookie to the
computer. PHP contains setcookie function to create a cookie object to be
sent to the client along with HTTP response.
Creating Cookies with PHP
A cookie can be created with the setcookie() function.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters
Name − Name of the cookie stored.
Value − This sets the value of the named variable.
Expiry − This specifes a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
Path − Directories for which the cookie is valid.
Domain − Specifies the domain name in very large domains.
Security − 1 for HTTPS. Default 0 for regular HTTP.
Modifying a Cookie
Delete a Cookie
To delete a cookie, we need to use the setcookie() function with a date that
has already expired.
PHP Session
A session is a way to store information to be used across multiple pages.
Session variables store user information which can be used across multiple
pages. Session variables last until the user closes the browser.

Starting a PHP Session


In PHP a session can be started with the session_start() function. Sessions
variables are set with the $_SESSION variable.
Get PHP Session Variable Values

these variables are


from the previous
program
or we can use print_r() method
Modifying a Session Variable
Destroying a PHP Session
To delete all the session variables and destroy the session, we can use
session_unset() and session_destroy().

it will give a black screen if any message is given


in your code and says that the session is
destroyed
The End

You might also like