Web Technology
Web Technology
AJAX
Www.arjun00.com.np
XML AND AJAX
1.1 Introduction to XML
1.2 Working with Basics of XML
1.3 Converting XML Documents in other formats
1.4 Working with XSLT
1.5 Working with Xpath, Xlink and Xpointer
1.6 XML Application
1.7 Overview of AJAX
1.8 AJAX components
1.9 Asynchronous Data Transfer with XML Http request
1.10 Implementing AJAX Frameworks
1.11 Consuming web services using AJAX
Www.arjun00.com.np
INTRODUCTION TO
XML
Introduction
XML, or Extensible Markup Language, is a markup language that
you can use to create your own tags. It was created by the World
Wide Web Consortium (W3C) to overcome the limitations of
HTML, the Hypertext Markup Language that is the basis for all
Web pages. Like HTML, XML is based on SGML -- Standard
Generalized Markup Language.
Www.arjun00.com.np
WHY DO WE NEED XML?
Www.arjun00.com.np
XML and HTML were designed with different goals:
1. XML is designed to carry data emphasizing on what type of
data it is.
2. HTML is designed to display data emphasizing on how data
looks
3. XML tags are not predefined like HTML tags.
4. HTML is a markup language whereas XML provides a
framework for defining markup languages.
5. HTML is about displaying data,hence it is static whereas XML
is about carrying information,which makes it dynamic.
Www.arjun00.com.np
There are three important characteristics of XML that make it
useful in a variety of systems and solutions −
XML is extensible − XML allows you to create your own self-
descriptive tags, or language, that suits your application.
XML carries the data, does not present it − XML allows you to
store the data irrespective of how it will be presented.
XML is a public standard − XML was developed by an
organization called the World Wide Web Consortium (W3C) and is
available as an open standard.
Www.arjun00.com.np
XML USAGE
Www.arjun00.com.np
XML DOES NOT USE
PREDEFINED TAGS
Www.arjun00.com.np
XML IS EXTENSIBLE
Www.arjun00.com.np
<note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
Www.arjun00.com.np
Books.xml
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Www.arjun00.com.np
IS XML A PROGRAMMING
LANGUAGE?
Www.arjun00.com.np
XML - SYNTAX
Www.arjun00.com.np
XML DECLARATION
Www.arjun00.com.np
TAGS AND ELEMENTS
Www.arjun00.com.np
XML ATTRIBUTES
Www.arjun00.com.np
XML REFERENCES
Www.arjun00.com.np
XML TEXT
Www.arjun00.com.np
HOW TO CONVERT AN
XML FILE
The best solution to converting an XML file to another format is to use one of the
editors . The program that's creating the XML file is more than likely able to save
the same file to a different format.
For example, a simple text editor, which can open a text document like XML, can
usually save the file to another text-based format like TXT.
Here are some other free online XML converters that might be more useful for
you:
XML to HTML
XML to CSV
XML to XSD
XML to PDF
Here are some free converters that convert to XML instead of from XML:
XLS/XLSX to XML
SQL to XML
CSV to XML
JSON to XML
Www.arjun00.com.np
WORKING WITH XSLT
XSL
XSL which stands for EXtensible Stylesheet Language. It is similar to XML
as CSS is to HTML.
Need for XSL
In case of HTML document, tags are predefined such as table, div, and span;
and the browser knows how to add style to them and display those using
CSS styles. But in case of XML documents, tags are not predefined. In order
to understand and style an XML document, World Wide Web Consortium
(W3C) developed XSL which can act as XML based Stylesheet Language. An
XSL document specifies how a browser should render an XML document.
Following are the main parts of XSL −
XSLT − used to transform XML document into various other types of
document.
XPath − used to navigate XML document.
XSL-FO − used to format XML document.
Www.arjun00.com.np
WHAT IS XSLT
Www.arjun00.com.np
Www.arjun00.com.np
Advantages
Here are the advantages of using XSLT −
-Independent of programming. Transformations are written in a
separate xsl file which is again an XML document.
-Output can be altered by simply modifying the transformations in
xsl file. No need to change any code. So Web designers can edit
the stylesheet and can see the change in the output quickly.
Www.arjun00.com.np
XSLT SYNTAX
Www.arjun00.com.np
students.xml
<?xml version = "1.0"?>
<class>
<student rollno = "393"> <firstname>Dinkar</firstname>
<lastname>Kad</lastname> <nickname>Dinkar</nickname>
<marks>85</marks> </student>
<student rollno = "493"> <firstname>Vaneet</firstname>
<lastname>Gupta</lastname> <nickname>Vinni</nickname>
<marks>95</marks> </student>
<student rollno = "593"> <firstname>Jasvir</firstname>
<lastname>Singh</lastname> <nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
Www.arjun00.com.np
We need to define an XSLT style sheet document for the above
XML document to meet the following criteria −
Page should have a title Students.
Page should have a table of student details.
Columns should have following headers: Roll No, First Name,
Last Name, Nick Name, Marks
Table must contain details of the students accordingly.
Step 1: Create XSLT document
Create an XSLT document to meet the above requirements, name
it as students.xsl and save it in the same location where
students.xml lies.
Www.arjun00.com.np
WHAT IS XPATH?
Www.arjun00.com.np
XPath is a language for addressing specific parts of a document. XPath
models an XML document as a tree of nodes. An XPath expression is a
mechanism for navigating through and selecting nodes from the document.
An XPath expression is, in a way, analogous to an SQL query used to select
records from a database.
There are various types of nodes, including element nodes, attribute nodes,
and text nodes. XPath defines a way to compute a string-value for each type
of node.
XPath defines a library of standard functions for working with strings,
numbers and boolean expressions.
Examples:
child::* - Selects all children of the root node.
.//name - Selects all elements having the name "name", descendants of the
current node.
/catalog/cd[price>10.80] - Selects all the cd elements that have a price
element with a value larger than 10.80.
Www.arjun00.com.np
XLINK
Www.arjun00.com.np
XLINK BROWSER
SUPPORT
Www.arjun00.com.np
<?xml version="1.0" encoding="UTF-8"?>
<homepages xmlns:xlink="http://www.w3.org/1999/xlink">
<homepage xlink:type="simple" xlink:href="https://www.w3school
s.com">Visit W3Schools</homepage>
<homepage xlink:type="simple" xlink:href="http://www.w3.org">V
isit W3C</homepage>
</homepages>
Www.arjun00.com.np
To get access to the XLink features we must declare the XLink
namespace. The XLink namespace is:
"http://www.w3.org/1999/xlink".
The xlink:type and the xlink:href attributes in the <homepage>
elements come from the XLink namespace.
The xlink:type="simple" creates a simple "HTML-like" link (means
"click here to go there").
The xlink:href attribute specifies the URL to link to.
Www.arjun00.com.np
XLink Example
The following XML document contains XLink features:
Www.arjun00.com.np
Www.arjun00.com.np
Example explained:
The XLink namespace is declared at the top of the document
(xmlns:xlink="http://www.w3.org/1999/xlink")
The xlink:type="simple" creates a simple "HTML-like" link
The xlink:href attribute specifies the URL to link to (in this case -
an image)
The xlink:show="new" specifies that the link should open in a new
window
Www.arjun00.com.np
XPOINTER
Www.arjun00.com.np
XPOINTER BROWSER
SUPPORT
Www.arjun00.com.np
Www.arjun00.com.np
Www.arjun00.com.np
WHAT IS AJAX?
Www.arjun00.com.np
AJAX is Based on Open Standards
AJAX is based on the following open standards −
Browser-based presentation using HTML and Cascading Style
Sheets (CSS).
Data is stored in XML format and fetched from the server.
Behind-the-scenes data fetches using XMLHttpRequest objects in
the browser.
JavaScript to make everything happen.
Www.arjun00.com.np
THE ORIGINS OF AJAX
Www.arjun00.com.np
Since data can be sent and retrieved without requiring the user to reload an
entire Web page, small amounts of data can be transferred as and when
required. Moreover, page elements can be dynamically refreshed at any level
of granularity to reflect this. An AJAX application performs in a similar way to
local applications residing on a user’s machine, resulting in a user experience
that may differ from traditional Web browsing.
Examples of AJAX usage include GMail and Flickr. It is largely due to these and
other prominent sites that AJAX has become popular only relatively recently –
the technology has been available for some time. One precursor was dynamic
HTML (DHTML), which twinned HTML with CSS and JavaScript but suffered
from cross-browser compatibility issues.
AJAX is not a technology, rather, the term refers to a proposed set of methods
using a number of existing technologies. As yet, there is no firm AJAX standard,
although the recent establishment of the Open AJAX Alliance [2], supported by
major industry figures such as IBM and Google, suggests that one will become
available soon.
Www.arjun00.com.np
ADVANTAGES AND
DISADVANTAGES OF AJAX
Www.arjun00.com.np
The disadvantages include:
1. Clicking the browser's "back" button may not function as expected.
2. Dynamic Web page updates make it difficult for a user to use
bookmarks.
3. Browser does not support JavaScript or have JavaScript disabled,
will not be able to use its functionality.
4. AJAX may provide a mechanism for attacks by malicious code
Www.arjun00.com.np
AJAX - EXAMPLES
Here is a list of some famous web applications that make use of AJAX.
Google Maps
A user can drag an entire map by using the mouse, rather than clicking on a
button.
https://maps.google.com/
Google Suggest
As you type, Google offers suggestions. Use the arrow keys to navigate the
results.
https://www.google.com/webhp?complete=1&hl=en
Gmail
Gmail is a webmail built on the idea that emails can be more intuitive,
efficient, and useful.
https://gmail.com/
Www.arjun00.com.np
Yahoo Maps (new)
Now it's even easier and more fun to get where you're going!
https://maps.yahoo.com/
Www.arjun00.com.np
ASYNCHRONOUS DATA
TRANSFER WITH
XMLHTTP REQUEST
Www.arjun00.com.np
IMPLEMENTING AJAX
FRAMEWORK
The AJAX Framework is a cross browser framework that allows
developers to quickly develop web pages that can call web
services, web pages and other types of content through
JavaScript without having to submit the current page.The AJAX
Framework is:
Easy to use.
Works well with other existing frameworks.
Supports both "GET" and "POST".
Works with Internet Explorer 6+, Opera 8+, Safari 3+, Firefox 2+,
Google's Chrome and other Mozilla based browsers.
Www.arjun00.com.np
CONSUMING WEB
SERVICES USING AJAX
Www.arjun00.com.np
INTRODUCTION
TO PHP
WWW.ARJUN00.COM.NP
INTRODUCTION TO
PHP
2.1 Introduction to PHP Scripting Language
2.2 PHP vs JSP vs ASP server-side programming
2.3 Server-Side Scripting vs Client-Side Scripting
2.4 Installing XAMPP or WAMP or other web server
2.5 Setting server environment
2.6 Configuration and Adjusting setting in PHP.ini and httpd.conf
2.7 Running PHP scripts
2.8 Formatting outputs
2.9 Working with variables, global variables and constants
210 Logical, concatenation, mathematical and relational
operators
2.11 Escape Sequences
WWW.ARJUN00.COM.NP
WHAT IS PHP?
WWW.ARJUN00.COM.NP
USES OF PHP
To further fortify your trust in PHP, here are a few applications of this
amazing scripting language:
1. It can be used to create Web applications like Social
Networks(Facebook, Digg), Blogs(Wordpress, Joomla),
eCommerce websites(OpenCart, Magento etc.) etc.
2. Comman Line Scripting. You can write PHP scripts to perform
different operations on any machine, all you need is a PHP
parser for this.
3. Create Facebook applications and easily integrate Facebook
plugins in your website, using Facebook's PHP SDK.
4. Sending Emails or building email applications because PHP
provides with a robust email sending function.
5. Wordpress is one of the most used blogging(CMS) platform in
the World, and if you know PHP, you can try a hand
in Wordpress plugin development.
WWW.ARJUN00.COM.NP
WHAT SHOULD I KNOW
BEFORE LEARNING PHP
WWW.ARJUN00.COM.NP
WHO IS USING PHP?
WWW.ARJUN00.COM.NP
ADVANTAGES OF PHP OVER
OTHER LANGUAGES
WWW.ARJUN00.COM.NP
Php Syntax
<?php
echo ‘Hello world’;
?>
A PHP file can also contain tags such as HTML and client side scripts
such as JavaScript.
HTML is an added advantage when learning PHP Language. You can
even learn PHP without knowing HTML but it’s recommended you at
least know the basics of HTML.
Database management systems DBMS for database powered
applications.
For more advanced topics such as interactive applications and web
services, you will need JavaScript and XML.
The flowchart diagram shown below illustrates the basic architecture of
a PHP web application and how the server handles the requests.
WWW.ARJUN00.COM.NP
WWW.ARJUN00.COM.NP
PHP VS JSP VS ASP
SERVER-SIDE
PROGRAMMING
The table below compares the various server side scripting
languages with PHP
WWW.ARJUN00.COM.NP
WWW.ARJUN00.COM.NP
SERVER-SIDE SCRIPTING VS
CLIENT-SIDE SCRIPTING
The scripts can be written in two forms, at the server end (back end)
or at the client end (server end). The main difference between
server-side scripting and client-side scripting is that the server side
scripting involves server for its processing. On the other hand, client-
side scripting requires browsers to run the scripts on the client
machine but does not interact with the server while processing the
client-side scripts.
WWW.ARJUN00.COM.NP
WWW.ARJUN00.COM.NP
INSTALLING XAMPP OR WAMP OR
OTHER WEB SERVER
WWW.ARJUN00.COM.NP
WHAT IS XAMPP?
WWW.ARJUN00.COM.NP
You can easily download and install XAMPP from this link. The
installation process is simple and once installed you will see a
small window like this, showing the status of various services
which are running.
WWW.ARJUN00.COM.NP
You can easily control, stop and restart, various services using the
XAMPP Control Panel.
Upon successful installation, a folder with name xampp will be created
in the C drive(by default). In the folder xampp there are many sub-
folders like apache, cgi-bin, FileZillaFTP etc, but the most important
sub-folders are:
htdocs: This is the folder in which we will keep all our PHP files.
mysql: This folder contains all the files for the MySQL database. By
default the MySQL databse runs on port number 3306.
php: This folder holds all the installation files for PHP. All the
configurations for the current PHP installation is saved in php.ini file
which is stored in this folder.
If everything seems fine and the apache server is running(check in the
XAMPP control panel), open your Web browser and enter localhost in
the address bar and hit enter. You will see the default page of Apache
web server.
WWW.ARJUN00.COM.NP
Other Software Packages
XAMPP is not the only available package, although it is the most
widely used one. Here are a few other Operating System specific
options that you can download and install:
WAMP: It's for Windows (Window, Apache, MySQL and PHP)
MAMP: It's for Mac OSX (Macintosh, Apache, MySQL and PHP)
LAMP: It's for Linux (Linux, Apache, MySQL and PHP)
WWW.ARJUN00.COM.NP
IDE or Editor for writing PHP code
As PHP code is not compiled, you can even use a simple editor like Notepad
to create PHP code files. But it's always good to have a nice looking Editor
which can highlight the code, provide you suggestions while coding, and
even analyze your code for syntax errors as your write it.
So here are a few good IDEs and Editors:
Netbeans IDE
Eclipse IDE
PyStorm IDE
Atom Editor
Brackets Editor
Notepad ++
Sublime Text
WWW.ARJUN00.COM.NP
FIRST PHP EXAMPLE
WWW.ARJUN00.COM.NP
If we want to include this php code in an HTML document, we can
do so like this:
<!DOCTYPE>
<html>
<body>
<?
php echo "<h1>Hello, World!</h1>";
?>
</body>
</html>
WWW.ARJUN00.COM.NP
Now copy the above code and paste it in you Code Editor or IDE
and save the file with the name hello_world.php
Now go to your C directory where XAMPP was installed, and
open xampp → htdocs and create a new folder with
name studytonight and put your php code
file hello_world.php in the studytonight folder.
Now visit the following link in your
browser: localhost/studytonight/hello_world.php and you
would see Hello, World! written on the screen. Notice that Hello,
World! is written as a heading because in the HTML code we
specified that Hello, World! should be printed as a heading as put
it inside the heading tag <h1>
WWW.ARJUN00.COM.NP
WWW.ARJUN00.COM.NP
PHP SYNTAX RULES
Below we have a listed down the main syntax rules that you must
follow while writing php code.
1. All the php code in a php script should be enclosed
within <?php and ?>, else it will not be considered as php
code. Adding php code inside the PHP tags is known
as Escaping to php.<?php ... ?>
Apart from the standard <?php and ?>, you can also use
the Short-open tags:
<? ... ?>Or use the HTML script tags, like we do for
adding javascript code in HTML document:
<script language="PHP"> ... </script>
WWW.ARJUN00.COM.NP
2. Every expression in PHP ends with a semicolon ;
3. Commenting PHP code: Both single line and multi-line comments are supported in PHP.
For single line comment, we can either use # or // before the comment line. For example,
<?php
# This is also a single line comment
# another line of comment
// This is a single line comment
echo "Example for Single line Comments";
?>
And for multi-line comments, we use /* ... */. For example,
<?php
/* This is also a single line comment another line of comment */
echo "Example for Multi-line Comments";
?>
WWW.ARJUN00.COM.NP
4. PHP is case sensitive, which means that a variable $tiger is
not same as $Tiger. Both of these, represent two different
variables here.But all the predefined keywords and functions
like if, else, echo etc are case insensitive.
<?php
echo "Hello, World!";
ECHO "Hello, World!";
?>
OUTPUT
Hello, World! Hello, World!
WWW.ARJUN00.COM.NP
5. PHP uses curly braces to define a code block.
<?php
if($zero == 0)
{
echo "If condition satisfied";
echo "This is a code block";
}
?>
Don't worry we will learn about if...else conditions in details, this is
just to demonstrate the use of curly braces.
WWW.ARJUN00.COM.NP
PHP - VARIABLES
PHP variables are just a name for a value and you can simply use
it like this $var_name = value;. They usually store sting characters
and numeric values for later use in the programming block. Here
is a simple example:
WWW.ARJUN00.COM.NP
WHAT IS A VARIABLES
SCOPE TYPES IN PHP?
WWW.ARJUN00.COM.NP
SPECIAL KEYWORDS FOR DECLARING
VARIABLES SOCPES
WWW.ARJUN00.COM.NP
On the other side static keyword is used to store a value of a
varible declared inside a function, for consecutive cals. Normally
all the local variable are resseted when the fnction closes, unless
static keyword is used.
WWW.ARJUN00.COM.NP
RULES FOR CREATING
VARIABLES IN PHP
Here we have a few basic rules that you must keep in mind while
creating variables in PHP. All the rules are explained with help of
simple examples.
A variable name will always start with a $ sign, followed by the
variable name.
A variable name should not start with a numeric value. It can
either start with an alphabet or an underscore sign _.
WWW.ARJUN00.COM.NP
A variable name can only contain alphabets, numbers and
underscore symbol _.
Variable names in PHP are case-sensitive, which means $love is
not same as $Love.
WWW.ARJUN00.COM.NP
PHP ECHO AND PRINT FUNCTIONS
https://www.studytonight.com/php/php-echo-and-print
WWW.ARJUN00.COM.NP
PHP VARIABLES
Variables are "containers" for storing information. A variable can
have a short name (like x and y) or a more descriptive name (age,
carname, total_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)
WWW.ARJUN00.COM.NP
ADD TWO NUMBER
<html>
<body>
<?php
$a =5 ;
$b=6;
$c=$a+$b;
echo "The sum of $a and $b is $c”;
?>
</body>
</html>
Output:
The sum of 5 and 6 is 11
WWW.ARJUN00.COM.NP
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 used.
PHP has three different variable scopes:
local
global
static
WWW.ARJUN00.COM.NP
GLOBAL AND LOCAL SCOPE
A variable declared outside a function has a GLOBAL SCOPE and can
only be accessed outside a function:
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
Output:
WWW.ARJUN00.COM.NP
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
<html>
<body>
<?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>";
?>
</body>
</html>
Output:
Variable x inside function is: 5
Variable x outside function is:
WWW.ARJUN00.COM.NP
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:
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++; Output:
} 0
1
myTest();
2
echo "<br>";
myTest();
echo "<br>";
myTest();
?
BY>LECTURER SURAJ PANDEY CCT COLLEGE
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):
<html>
<body>
<?php
$x = 5;
$y = 10; Output:
15
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
WWW.ARJUN00.COM.NP
echo $y; // output the new value for variable $y
PHP ECHO AND PRINT FU
NCTIONS
PHP Echo
echo() function is used to print or output one or more strings. We
have specifically mentioned string here because, the syntax of
the echo function is:
echo(string)
Although you can use echo() function to output anything, as PHP
parser will automaticallly convert it into string type.
echo doesn't need parenthesis, although you can use parenthesis if
you want.
<?php
echo "I am open";
echo ("I am enclosed in parenthesis");
?>
CO
I am open I am enclosed in parenthesis
EXAMPLE
CO
PHP Print
The PHP print is exactly the same as echo, with same syntax and
same usage. Just replace echo with print in all the above
examples, and they will work just fine.
CO
PHP - CONSTANTS
CO
Let's take a closer look at
the examples above. We
used the define() function
to create the constant and
with the following params:
name - the defined name
for our constant
value - the defined value
for our constant
case-sensitive - this is an
optional param and it is
true by default. This means
that our constant is case
sensitive. Set it to false if
you need it
CO
Naming constants
Just like a normal variable a valid constant name starts with a
letter or underscore. On the other hand, a PHP constant doesn't
need the "$" sign before the constant name.
Although it is not a must, there is a convention that constant
names to be written in uppercase letters. This makes it easy for
the identification and distinguishes them from other variables
when reviewing coding documents.
Constants scope
Constants are automatically defined as globals and can be
directly used anywhere around the script without further action.
CO
CO
Check if a constant has been defined
Although we have not wet talked about the if/else tag yet, this is a
good place to mention that constants have a specific function to
check if they are defined.
For variables we will use isset() while for constants we will
use defined(). Here is an example using it on a constant:
CO
DATA TYPES IN PHP
PHP Data types specify the different types of data that are
supported in PHP language. There are total 8 data types
supported in PHP, which are categorized into 3 main types. They
are:
Scalar Types: boolean, integer, float and string.
Compound Types: array and object.
Special Types: resource and NULL.
CO
PHP Boolean
A boolean data type can have two possible values, either True or False.
$a = true;
$b = false;
NOTE: Here the values true and false are not enclosed within quotes,
because these are not strings.
PHP Integer
An Integer data type is used to store any non-decimal numeric value
within the range -2,147,483,648 to 2,147,483,647.
An integer value can be negative or positive, but it cannot have a
decimal.
$x = -2671;
$y = 7007;
CO
PHP Float
Float data type is used to store any decimal numeric value.
A float(floating point) value can also be either negative or positive.
$a = -2671.01;
$b = 7007.70;
PHP String
String data type in PHP and in general, is a sequence of characters(or
anything, it can be numbers and special characters too) enclosed within
quotes. You can use single or double quotes.
$str1 = "Hello";
$str2 = "What is your Roll No?";
$str3 = "4";
OUTPUT
echo $str1;
Hello What is your Roll No?
echo "<br/>"; Me: My Roll number is 4
echo $str2;
echo "<br/>";
echo "Me: My Roll number is $str3";
CO
PHP NULL
NULL data type is a special data type which means nothing. It
can only have one value, and that is NULL.
If you create any variable and do not assign any value to it, it will
automatically have NULL stored in it.
Also, we can use NULL value to empty any variable.
// holds a null value
$a;
$b = 7007.70;
// we can also assign null value
$b = null;
CO
PHP resource data type
A resource is a special variable, holding a reference to an external
resource like a database connection for example.
PHP$conn =
mysqli_connect(localhost,"root","admin","users");
CO
PHP OPERATORS
CO
There are a few additional operators as well like, Type operator,
Bitwise operator, Execution operators etc.
Based on how these operators are used, they are categorised into
3 categories:
Unary Operators: Works on a single operand(variable or value).
Binary Operators: Works on two operands(variables or values).
Ternary Operators: Works on three operands.
CO
PHP Arithmetic Operators
These operators are used to perform basic arithmetic operations
like addition, multiplication, division, etc.
CO
PHP Assignment Operators
Assignment operators are used to assign values to variables,
either as it is or after performing some arithmetic operation on it.
The most basic assignment operator is equal to=.
CO
PHP Comparison Operators
As the name suggest, these are used to compare two values.
WWW.ARJUN00.COM.NP
PHP Increment/Decrement Operators
These operators are unary operators, i.e they require only one
operand.
WWW.ARJUN00.COM.NP
PHP Logical Operators
Logical operators are generally used when any action depends on
two or more conditions.
WWW.ARJUN00.COM.NP
PHP String Operators
String operators are used to perform operations on string. There
are only two string operators, generally PHP built-in functions are
used to perform various operations on strings,
WWW.ARJUN00.COM.NP
WWW.ARJUN00.COM.NP
PHP Array Operators
These operators are used to compare arrays.
WWW.ARJUN00.COM.NP
ESCAPE SEQUENCE
Escape sequences are used for escaping a character during the
string parsing. It is also used for giving special meaning to
represent line breaks, tabs, alert and more. The escape
sequences are interpolated into strings enclosed by double
quotations or heredoc syntax.
Escape sequences are started with the escaping character
backslash (\) followed by the character which may be an
alphanumeric or a special character. If it is an alphanumeric
character, it gives special meaning to represent the line breaks \n,
carriage return \r and more. If it is a special character, then it will
be considered as it is during the string parsing. For example, if we
interpolate \$var into a string then it will be taken as $var. Without
the escaping character (\), the $var PHP variable is parsed to get
its value.
WWW.ARJUN00.COM.NP
Escape Sequence Example
This code shows a simple PHP example program to distinguish
the behavior of the escape sequences with alphanumeric and
non-alpha numeric characters. In this example, I used the escape
sequence \n to add a line break after label and I have used \\ to
escape \ character and print it to the browser.
<?php
echo "PHP Escape Sequences:\n Backslash \\ is used as an
escaping character.";
?>
WWW.ARJUN00.COM.NP
Widely used Escape Sequences in PHP
In this section, I have listed some of the widely used escape
sequences and describe how they are used to escape the special
character or to give meaning by combining with some
alphanumeric characters.
\’ – To escape ‘ within single quoted string.
\” – To escape “ within double quoted string.
\\ – To escape the backslash.
\$ – To escape $.
\n – To add line breaks between string.
\t – To add tab space.
\r – For carriage return.
WWW.ARJUN00.COM.NP
PROGRAMM
ING ON PHP
WWW.ARJUN00.COM.NP
PROGRAMMING ON
PHP
3.1 Conditional Statements(If, If else, switch statement)
3.2 Iteration and Looping (do while, while, for loop, foreach
loop)
3.3 Functions: Built-In and user-defined functions
3.4 String functions and pattern: String comparison, String
Concatenation.
3.5 Array: Numeric Array, Associative Array
3.6 One dimensional and multi-dimensional array
WWW.ARJUN00.COM.NP
CONDITIONAL
STATEMENT
While writing programs/scripts, there will be scenarios where you
would want to execute a particular statement only if some
condition is satisfied. In such situations we use Conditional
statements.
In PHP, there are 4 different types of Conditional Statements.
1. if statements
2. if...else statements
3. if...elseif...else statements
4. switch statement
WWW.ARJUN00.COM.NP
The if statement
When we want to execute some code when a condition is true, then we
use if statement.
Syntax:
if(condition)
{ // code to be executed if 'condition' is true }
Here is a simple example,
<?php
$age = 20;
if($age <= 25)
{
echo "You are not allowed to consume alchohol";
}
?>
WWW.ARJUN00.COM.NP
The if...else statement
When we want to execute some code when a condition is true, and some other
code when that condition is false, then we use the if...else pair.
Syntax:
if(condition)
{ // code to be executed if 'condition' is true }
else { // code to be executed if 'condition' is false }
Here is a simple example,
<?php
$age = 26;
if($age <= 25)
{
echo "You are not allowed to consume alchohol";
}
else
{
echo "Enjoy the drinks";
}
?>
WWW.ARJUN00.COM.NP
The if...else...elseif statement
When we want to execute different code for different set of conditions, and we have more than 2 possible conditions, then we
use if...elseif...else pair.
Syntax:
if(condition1)
{ // code to be executed if 'condition1' is true }
elseif(condition2)
{ // code to be executed if 'condition2' is true }
else { /* code to be executed if both 'condition1' and 'condition2' are false */ }
Here is a simple example,
<?php
// speed in kmph
$speed = 110;
if($speed < 60)
{
echo "Safe driving speed";
}
elseif($speed > 60 && $speed < 100)
{
echo "You are burning extra fuel";
}
else
{
// when speed is greater than 100
echo "Its dangerous";
}
?>
WWW.ARJUN00.COM.NP
The switch statement
A switch statement is used to perform different actions, based on different conditions.
Using a switch statement, we can specify multiple conditions along with the code to be executed
when that condition is true, thereby implementing a menu style program.
syntax:
switch(X)
{
case value1:
// execute this code when X=value1
break;
case value2:
// execute this code when X=value2
break;
case value3:
// execute this code when X=value3
break;
...
default:
/* execute this when X matches none of of the specified options */
}
WWW.ARJUN00.COM.NP
In a switch statement, we provide the deciding factor which can
be a variable or an expression to our switch statement, and then
we specify the different cases, each with a value, a piece of code
and a break statement.
break statement is specified to break the execution of the switch
statement once the action related to a specified value has been
performed.
If we do not specify a break statement, then all the switch cases,
after the matched case, will get executed, until the
next break statement.
The default statement is executed if no matching case is there.
WWW.ARJUN00.COM.NP
<?php
$car = "Jaguar";
switch($car)
{
case "Audi":
echo "Audi is amazing";
break;
case "Mercedes":
echo "Mercedes is mindblowing";
break;
case "Jaguar":
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
?>
Jaguar is the best
WWW.ARJUN00.COM.NP
ITERATION AND
LOOPING
As the name suggests, a Loop is used to execute something over
and over again.
For example, if you want to display all the numbers from 1 to
1000, rather than using echo statement 1000 times, or specifying
all the numbers in a single echo statement with newline
character \n, we can just use a loop, which will run for 1000 times
and every time it will display a number, starting from 1,
incrementing the number after each iteration or cycle.
In a Loop, we generally specify a condition or a LIMIT up till which
the loop will execute, because if we don't specify such a condition,
how will we specify when the loop should end and not go on for
infinite time.
WWW.ARJUN00.COM.NP
WWW.ARJUN00.COM.NP
PHP while Loop
The while loop in PHP has two components, one is a condition and
other is the code to be executed. It executes the given code until the
specified condition is true.
Syntax:
<?php
while(condition)
{
/* execute this code till the condition is true */
}
?>
For example, Let's print numbers from 1 to 10.
WWW.ARJUN00.COM.NP
<?php
$a = 1;
while($a <= 10)
{
echo "$a | ";
$a++;
// incrementing value of a by 1
}
?>
OUTPUT
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
WWW.ARJUN00.COM.NP
PHP do...while Loop
The do...while loop is a little different from all the loops in PHP because it will
execute at least one time, even if the condition is false, can you guess how?
Well because the condition is checked after the loop's execution, hence the
first time when the condition is checked, the loop has already executed once.
Syntax:
<?php
Do
{
/* execute this code till the condition is true */
}
while(condition)
?>
WWW.ARJUN00.COM.NP
Let's implement the above example using do...while loop,
<?php
$a = 1;
do
{ echo "$a | ";
$a++;
// incrementing value of a by 1
}
while($a <= 10)
?>
OUTPUT
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
WWW.ARJUN00.COM.NP
Let's take another example where even if the condition is false, still the loop will be executed
once.
<?php
$a = 11;
do
{
echo $a;
$a++;
// incrementing value of a by 1
}
while($a <= 10)
?>
OUTPUT
11
WWW.ARJUN00.COM.NP
As we can see clearly, that the condition in the
above do...while loop will return false because value of
variable $a is 11 and as per the condition the loop should be
executed only if the value of $a is less than or equal to 10.
WWW.ARJUN00.COM.NP
PHP for Loop
The for loop in PHP doesn't work like while or do...while loop, in
case of for loop, we have to declare beforehand how many times
we want the loop to run.
Syntax:
<?php
for(initialization; condition; increment/decrement)
{
/* execute this code till the condition is true */
}
?>
WWW.ARJUN00.COM.NP
The parameters used have following meaning:
initialization: Here we initialize a variable with some value. This
variable acts as the loop counter.
condition: Here we define the condition which is checked after
each iteration/cycle of the loop. If the condition returns true, then
only the loop is executed.
increment/decrement: Here we increment or decrement the loop
counter as per the requirements.
WWW.ARJUN00.COM.NP
print numbers from 1 to 10, this time we will be using the for loop.
<?php
for($a = 1; $a <= 10; $a++)
{
echo "$a <br/>";
}
?>
1
2
3
4
5
6
7
8
9
10
WWW.ARJUN00.COM.NP
Nested for Loops
We can also use a for loop inside another for loop. Here is a simple example of
nested for loops.
<?php
for($a = 0; $a <= 2; $a++)
{
for($b = 0; $b <= 2; $b++)
{
echo "$b $a ";
}
}
?>
0
0
1
0
2
0011121021222
WWW.ARJUN00.COM.NP
foreach Loop
The foreach loop in PHP is used to access key-value pairs of an
array. This loop only works with arrays and you do not have to
initialise any loop counter or set any condition for exiting from the
loop, everything is done implicitly(internally) by the loop.
Syntax:
<?php
foreach($array as $var)
{
/* execute this code for all the array elements $var will represent
all the array elements starting from first element, one by one */
}
?>
WWW.ARJUN00.COM.NP
Here is a simple example.
<?php
$array = array("Jaguar", "Audi", "Mercedes", "BMW"); foreach($array
as $var)
{
echo "$var <br/>";
}
?>
OUTPUT
Jaguar
Audi
Mercedes
BMW
WWW.ARJUN00.COM.NP
break statement
We have already seen and used break statements in
the switch conditional statements.
To recall, in switch code blocks, we used break statement to break
out of the switch block when a valid case block gets executed.
Let's see an example for simple switch code:
WWW.ARJUN00.COM.NP
<?php
$a = 1;
switch($a)
{
case 1: echo "This is case 1";
break;
case 2: echo "This is case 2";
break;
default: echo "This is default case";
}
?>
OUTPUT
This is case 1
WWW.ARJUN00.COM.NP
FUNCTIONS: BUILT-IN
AND USER-DEFINED
FUNCTIONS
A Function is nothing but a 'block of statements' which generally
performs a specific task and can be used repeatedly in our
program. This 'block of statements' is also given a name so that
whenever we want to use it in our program/script, we can call it by
its name.
In PHP there are thousands of built-in functions which we can
directly use in our program/script.
PHP also supports user defined functions, where we can define
our own functions.
A function doesn't execute when its defined, it executed when it is
called.
WWW.ARJUN00.COM.NP
PHP User Defined Functions
Let's understand how we can define our own functions in our
program and use those functions.
Syntax:
<?php
function function_name()
{
// function code statements
}
?>
WWW.ARJUN00.COM.NP
Few Rules to name Functions
1. A function name can only contain alphabets, numbers and
underscores. No other special character is allowed.
2. The name should start with either an alphabet or an
underscore. It should not start with a number.
3. And last but not least, function names are not case-sensitive.
4. The opening curly brace { after the function name marks the
start of the function code, and the closing curly brace } marks
the end of function code.
WWW.ARJUN00.COM.NP
write a very simple function which will display a simple "Merry
Christmas and a Very Happy New Year" message. This script can
actually be very useful when you have to send festive emails to
every friend of yours and you have to write the same message in all
of them.
WWW.ARJUN00.COM.NP
Advantages of User-defined Functions
As we have already seen a simple example of using a function
above, you must have understood how time-saving it can be for large
programs. Here are a few advantages of using functions for you:
Reuseable Code: As it's clear from the example above, you write a
function once and can use it for a thousand times in your program.
Less Code Repetition: In the example above we just had one line of
code in the function, but what if we have 10 lines of code. So rather
than repeating all those lines of code over and over again, we can
just create a function for them and simply call the function.
Easy to Understand: Using functions in your program, makes the
code more readable and easy to understand.
WWW.ARJUN00.COM.NP
PHP Function Arguments
We can even pass data to a function, which can be used inside the function
block. This is done using arguments. An argument is nothing but a variable.
Arguments are specified after the function name, in parentheses, separated
by comma. When we define a function, we must define the number of
arguments it will accept and only that much arguments can be passed while
calling the function.
Syntax:
<?php
/* we can have as many arguments as we want to have in a function */
function function_name(argument1, argument2)
{
// function code statements
}
?>
WWW.ARJUN00.COM.NP
<?php
// defining the function with argument function greetings($festival)
{
echo "Wish you a very Happy $festival";
}
echo "Hey Jai <br/>";
// calling the function
greetings("Diwali");
// next line
echo "<br/>";
echo "Hey Jon <br/>";
// calling the function again
greetings("New Year");
?>
WWW.ARJUN00.COM.NP
PHP Default Function Arguments
Sometimes function arguments play an important role in the
function code execution. In such cases, if a user forgets to provide
the argument while calling the function, it might lead to some
error.
To avoid such errors, we can provide a default value for the
arguments which is used when no value is provided for the
argument when the function is called.
Let's take an example.
WWW.ARJUN00.COM.NP
<?php
// defining the function with default argument function greetings($festival = "Life")
{
echo "Wish you a very Happy $festival";
}
echo "Hey Jai <br/>";
// calling the function with an argument
greetings("Diwali");
// next line
echo "<br/>";
echo "Hey Jon <br/>";
// and without an argument
greetings();
?>
WWW.ARJUN00.COM.NP
PHP Function Returning Values
Yes, functions can even return results. When we have functions which are
defined to perform some mathematical operation etc, we would want to output
the result of the operation, so we return the result.
return statement is used to return any variable or value from a function in PHP.
Let's see an example.
<?php
function add($a, $b)
{
$sum = $a + $b;
// returning the result
return $sum;
}
echo "5 + 10 = " . add(5, 10) . "";
?>
OUTPUT
5 + 10 = 15
WWW.ARJUN00.COM.NP
PHP Function Overloading
Function overloading allows you to have multiple different variants
of one function, differentiated by the number and type of
arguments they take.
For example, we defined the function add() which takes two
arguments, and return the sum of those two. What if we wish to
provide support for adding 3 numbers.
To tackle such situations, what we can do is, we can define two
different variants of the function add(), one which takes in 2
arguments and another which accepts 3 arguments. This is
called Function Overloading.
Let's take an example,
WWW.ARJUN00.COM.NP
<?php
// add function with 2 arguments
function add($a, $b)
{
$sum = $a + $b;
// returning the result return $sum;
}
// overloaded add function with 3 arguments
function add($a, $b, $c)
{
$sum = $a + $b + $c;
// returning the result
return $sum;
}
// calling add with 2 arguments
echo "5 + 10 = " . add(5, 10) . "<br/>";
// calling add with 3 arguments
echo "5 + 10 + 15 = " .add(5, 10, 15) . "<br/>";
?>
WWW.ARJUN00.COM.NP
STRING FUNCTIONS AND PATTERN: STRING
COMPARISON, STRING CONCATENATION.
WWW.ARJUN00.COM.NP
We can define a string using double quotes as well as single
quotes.
But, what if the string has a single or double quote in it, then
what?
<?php
$srt1 = "This is "a" String";
$str2 = 'This is also 'a' String';
?>
WWW.ARJUN00.COM.NP
Both the above string definitions will result in error, as we cannot
include a double quote in the string, if the string is defined inside
double quotes.
But it will work, if the string contains double quotes, but it is
defined using single quotes and vice versa, for example,
<?php
// string inside double quotes, with a single quote
$srt1 = "This is 'a' String"; // string inside single quotes, with
a double quote
$str2 = 'This is also "a" String';
?>
WWW.ARJUN00.COM.NP
There is one more simple technique to deal with the quotes problem, it is
known as Escaping Special Character, which can be done using
a backslash.
Let's take an example,
<?php
// escaping double quote using backslash
$srt1 = "I\"ll handle this.";
// escaping single quote using backslash
$str2 = 'I\'ll handle this.';
echo $str1;
echo "\n"; // new line
echo $str2;
?>
WWW.ARJUN00.COM.NP
STRING FUNCTIONS
In general practice, using the right string function will save you a
lot of time as they are pre-defined in PHP libraries and all you
have to do is call them to use them.
WWW.ARJUN00.COM.NP
strlen($str)
This function returns the length of the string or the number of
characters in the string including whitespaces
<?php
$str = "Welcome to Studytonight";
// using strlen in echo method
echo "Length of the string is: ". strlen($str);
?>
OUTPUT
WWW.ARJUN00.COM.NP
str_word_count($str)
This function returns the number of words in the string. This function
comes in handly in form field validation for some simple validations.
<?php
$str = "Welcome to Studytonight";
// using str_word_count in echo method
echo "Number of words in the string are: ".
str_word_count($str);
?>
OUTPUT
Number of words in the string are: 3
WWW.ARJUN00.COM.NP
strrev($str)
This function is used to reverse a string.
Let's take an example and see,
<?php
$str = "Welcome to Studytonight";
// using strrev in echo method
echo "Reverse: ". strrev($str);
?>
OUTPUT
Reverse: thginotydutS ot emocleW
WWW.ARJUN00.COM.NP
strpos($str, $text)
This function is used to find the position of any text/word in a given
string. Just like an array, string also assign index value to the
characters stored in it, starting from zero.
<?php
$str = "Welcome to Studytonight";
// using strpos in echo method
echo "Position of 'Studytonight' in string: ". strpos($str,
'Studytonight');
?>
OUTPUT
Position of 'Studytonight' in string: 11
WWW.ARJUN00.COM.NP
Concatenation of two strings in PHP
There are two string operators. The first is the concatenation operator
(‘.‘), which returns the concatenation of its right and left arguments.
The second is the concatenating assignment operator (‘.=‘), which
appends the argument on the right side to the argument on the left
side.
Examples :
Input : string1: Hello
string2 : World!
Output : HelloWorld!
Input : string1: geeksfor
string2: geeks
Output : geeksforgeeks
WWW.ARJUN00.COM.NP
Output
<?php :
HelloWorld!
// First String
$a = 'Hello';
// Second String
$b = 'World!';
// Concatenation Of String
$c = $a.$b;
WWW.ARJUN00.COM.NP
Output
<?php :
John Carter!
// First String
$fname = 'John';
// Second String
$lname = 'Carter!';
// Concatenation Of String
$c = $fname." ".$lname;
WWW.ARJUN00.COM.NP
Output
<?php :
HelloWorld!
// First String
$a = 'Hello';
WWW.ARJUN00.COM.NP
COMPARISON OF
STRING
== operator
The most common way you will see of comparing two strings is simply by
using the == operator if the two strings are equal to each other then it returns
true.
// Using the == operator, Strings match is printed
if('string1' == 'string1')
{
echo 'Strings match.';
}
else
{
echo 'Strings do not match.';
}
WWW.ARJUN00.COM.NP
// Using the == operator, Strings do not match is printed
if('string1' == 'STRING1')
{
echo 'Strings match.';
}
Else
{
echo 'Strings do not match.';
}
WWW.ARJUN00.COM.NP
strcmp Function
Another way to compare strings is to use the PHP function strcmp,
this is a binary safe string comparison function that will return a 0 if
the strings match.
// strcmp function, Strings match is printed if(strcmp('string1',
'string1') == 0)
{
echo 'Strings match.';
}
else
{
echo 'Strings do not match.';
}
WWW.ARJUN00.COM.NP
strcasecmp Function
The previous examples will not allow you to compare different
case strings, the following function will allow you to compare case
insensitive strings.
WWW.ARJUN00.COM.NP
// Both strings will match
if(strcasecmp('string1', 'string1') == 0)
{
echo 'Strings match.';
}
else
{
echo 'Strings do not match.';
}
// Both strings will match even with different case
if(strcasecmp('string1', 'String1') == 0)
{
echo 'Strings match.';
}
else
{ echo 'Strings do not match.';
}
// Both strings will match even with different case
if(strcasecmp('string1', 'STRING1') == 0)
{
echo 'Strings match.';
}
else
{
echo 'Strings do not match.';
}
WWW.ARJUN00.COM.NP
ARRAY: NUMERIC ARRAY,
ASSOCIATIVE ARRAY
Arrays in PHP is a type of data structure that allows us to store
multiple elements of similar data type under a single variable
thereby saving us the effort of creating a different variable for
every data.
An array is created using an array() function in PHP.
There are basically three types of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index
where values are stored linearly.
Associative Arrays: An array with a string index where instead of
linear storage, each value can be assigned a specific key.
Multidimensional Arrays: An array which contains single or
multiple array within it and can be accessed via multiple indices.
WWW.ARJUN00.COM.NP
Indexed or Numeric Arrays
These type of arrays can be used to store any type of elements,
but an index is always a number. By default, the index starts at
zero. These arrays can be created in two different ways as shown
in the following example:
WWW.ARJUN00.COM.NP
<?php
?>
WWW.ARJUN00.COM.NP
Associative Arrays
These type of arrays are similar to the indexed arrays but instead
of linear storage, every value can be assigned with a user-defined
key of string type.
Example:
WWW.ARJUN00.COM.NP
<?php
?>
WWW.ARJUN00.COM.NP
Associative arrays are used to store key value pairs. For example,
to store the marks of different subject of a student in an array, a
numerically indexed array would not be the best choice. Instead,
we could use the respective subject’s names as the keys in our
associative array, and the value would be their respective marks
gained.
Example:
Here array() function is used to create associative array.
WWW.ARJUN00.COM.NP
<?php
/* First method to create an associate array. */
$student_one = array("Maths"=>95, "Physics"=>90,
"Chemistry"=>96, "English"=>93,
"Computer"=>98);
WWW.ARJUN00.COM.NP
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Ganesh",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Saroj","mob"
=> "2584369721",
"email" => "[email protected]",
),
array(
"name" => "Arjun",
"mob" => "9875147536",
"email" => "[email protected]",
)
);
// Accessing elements
echo "Ganesh email-id is: " . $favorites[0]["email"], "\n"; echo
"Arjun mobile number is: " . $favorites[2]["mob"];
?>
WWW.ARJUN00.COM.NP
Multidimensional Arrays
Multi-dimensional arrays are such arrays which stores an another
array at each index instead of single element. In other words, we
can define multi-dimensional arrays as array of arrays. As the
name suggests, every element in this array can be an array and
they can also hold other sub-arrays within. Arrays or sub-arrays in
multidimensional arrays can be accessed using multiple
dimensions.
Example:
WWW.ARJUN00.COM.NP
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Ganesh",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Saroj","mob"
=> "2584369721",
"email" => "[email protected]",
),
array(
"name" => "Arjun","mob"
=> "9875147536",
"email" => "[email protected]",
)
);
// Accessing elements
echo "Ganesh email-id is: " . $favorites[0]["email"], "\n";
echo "Arjun mobile number is: " . $favorites[2]["mob"];
?>
WWW.ARJUN00.COM.NP
PROGRAMM
ING ON PHP
GET AND POST
We have two HTTP request methods in PHP for handling the
forms, where submitted form-data from users can be collected
using these methods. In order to send information to the web
server from the browser client, we use GET and POST methods.
GET Method: Data is requested from a specific resource
POST Method: Data is submitted to be processed to a specific
resource
The GET Method
The GET method sends the encoded user information appended
to the page request. The page and the encoded information are
separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
The POST Method
The POST method transfers information via HTTP headers. The
information is encoded as described in case of GET method and
put into a header called QUERY_STRING.
<?php
if( $_POST["name"] || $_POST["age"] )
{
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] ))
{
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both
$_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from
form data sent with both the GET and POST methods.
Try out following example by putting the source code in test.php
script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] )
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST"> Name:
<input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
FILE INCLUSION AND
FILES & I/O
PHP - File Inclusion
You can include the content of a PHP file into another PHP file
before the server executes it. There are two PHP functions which
can be used to included one PHP file into another PHP file.
The include() Function
The require() Function
The include() Function
The include() function takes all the text in a specified file and
copies it into the file that uses the include function. If there is any
problem in loading a file then the include() function generates a
warning but the script will continue execution.
Assume you want to create a common menu for your website.
Then create a file menu.php with the following content.
<a href="http://www.tutorialspoint.com/index.htm">Home</a>
- <a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> - <a
href="http://www.tutorialspoint.com/perl">PERL</a> <br />
Now create as many pages as you like and include this file to
create header. For example now your test.php file can have
following content.
<html>
<body>
<?php
include("menu.php");
?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
The require() Function
The require() function takes all the text in a specified file and
copies it into the file that uses the include function. If there is any
problem in loading a file then the require() function generates a
fatal error and halt the execution of the script.
You can try using above example with require() function and it will
generate same result. But if you will try following two examples where
file does not exist then you will get different results.
<html>
<body>
<?php
include("xxmenu.php");
?>
<p>This is an example to show how to include wrong PHP
file!</p>
</body>
</html>
Now lets try same example with require() function.
<html>
<body>
<?php
require("xxmenu.php");
?>
<p>This is an example to show how to include wrong PHP
file!</p>
</body>
</html>
PHP - FILES & I/O
function funcGeek()
{
echo "This is Geeks for Geeks";
}
?>
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:
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
USER DEFINED
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.
Function names are NOT case-sensitive.
Syntax
function functionName() {
code to be executed;
}
Www.arjun00.com.np
EXAMPLE OF USER DEFINED FUNCTIONS
<html>
<body>
<?php
function writeMsg() {
echo "Hello Nabraj!";
}
writeMsg();
?>
</body>
</html>
Output:
Hello Nabraj!
Www.arjun00.com.np
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.
Www.arjun00.com.np
FUNCTION ARGUMENTS
<html>
<body>
<?php
function familyName($fname) {
echo "$fname<br>";
}
familyName("Nabraj"); Output:
familyName("Ramesh"); Nabraj
Ramesh
familyName("Pawan"); Pawan
familyName("Nabin"); Nabin
familyName("Khim"); Khim
?>
</body>
</html>
Www.arjun00.com.np
FUNCTIONS - RETURNING VALUES
To let a function return a value, use the return statement:
<html>
<body>
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo sum(5,10);
echo "<br>";
echo sum(7,13);
?>
</body>
</html>
Output:
15
20
Www.arjun00.com.np
FUNCTION TO FIND AREA OF RECTANGLE
AND RETURN THE VALUE
<html>
<body>
<?php
function sum( int $l, int $b) {
$a = $l * $b;
return $a;
}
$b= sum(15,200);
echo $b;
?>
</body>
</html>
Www.arjun00.com.np
FUNCTION TO ADD TWO NUMBER
<html>
<body>
<?php
function sum(int $x, int $y) {
$z = $x + $y;
echo $z;
}
echo sum(5,10);
?>
</body>
</html>
Www.arjun00.com.np
COOKIE
What is a cookie
Cookies are used to store the information of a web page in a
remote browser, so that when the same user comes back to that
page, that information can be retrieved from the browser itself.
Www.arjun00.com.np
USES OF COOKIE
Cookies are often used to perform
following tasks:
Session management: Cookies are widely used to manage user sessions. For
example, when you use an online shopping cart, you keep adding items in the
cart and finally when you checkout, all of those items are added to the list of
items you have purchased. This can be achieved using cookies.
User identification: Once a user visits a webpage, using cookies, that user
can be remembered. And later on, depending upon the search/visit pattern of
the user, content which the user likely to be visited are served. A good
example of this is 'Retargetting'. A concept used in online marketing, where
depending upon the user's choice of content, advertisements of the relevant
product, which the user may buy, are served.
Tracking / Analytics: Cookies are used to track the user. Which, in turn, is
used to analyze and serve various kind of data of great value, like location,
technologies (e.g. browser, OS) form where the user visited, how long (s)he
stayed on various pages etc.
Www.arjun00.com.np
HOW TO CREATE A
COOKIE IN PHP
Www.arjun00.com.np
Example to Create/Retrieve a Cookie:
<html>
<?php
$cookie_name = "user";
$cookie_value = "Nabraj Koirala";
setcookie($cookie_name, $cookie_value, time() + 10);
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named " . $cookie_name . "'is not set!";
} else {
echo "Cookie " . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Www.arjun00.com.np
PHP SESSIONS
A session is a way to store information (in variables) to be used
across multiple pages.
Unlike a cookie, the information is not stored on the users
computer.
When you work with an 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.
Www.arjun00.com.np
Start a PHP Session:
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Www.arjun00.com.np
Get PHP Session Variable Values:
<?php
session_start();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Www.arjun00.com.np
DESTROY A PHP SESSION
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
Example
<?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "All session variables are now removed, and the session is destroyed."
?>
</body>
</html>
Www.arjun00.com.np
SENDING EMAILS
What is PHP mail?
PHP mail is the built in PHP function that is used to send emails
from PHP scripts.
The mail function accepts the following parameters;
Email address
Subject
Message
CC or BC email addresses
Sending mail using PHP
The PHP mail function has the following basic syntax
<?php
mail($to_email_address,$subject,$message,[$headers],[$par
ameters]);
?>
HERE,
“$to_email_address” is the email address of the mail recipient
“$subject” is the email subject
“$message” is the message to be sent.
“[$headers]” is optional, it can be used to include information such as
CC, BCC
• CC is the acronym for carbon copy. It’s used when you want to
send a copy to an interested person i.e. a complaint email sent
to a company can also be sent as CC to the complaints board.
• BCC is the acronym for blind carbon copy. It is similar to CC. The
email addresses included in the BCC section will not be shown
to the other recipients.
Simple Mail Transmission Protocol (SMTP)
PHP mailer uses Simple Mail Transmission Protocol (SMTP) to
send mail.
On a hosted server, the SMTP settings would have already been
set.
The SMTP mail settings can be configured from “php.ini” file in the
PHP installation folder.
Configuring SMTP settings on your localhost Assuming you are
using xampp on windows, locate the “php.ini” in the directory
“C:\xampp\php”.
Open it using notepad or any text editor. We will use notepad in
this example. Click on the edit menu
ocate the entries[mail function]
; XAMPP: Don’t remove the semi column if you want to work with an SMTP
Server like Mercury
; SMTP = localhost
; smtp_port = 25
Remove the semi colons before SMTP and smtp_port and set the SMTP to
your smtp server and the port to your smtp port. Your settings should look as
follows
• SMTP = smtp.example.com
• smtp_port = 25
• Note the SMTP settings can be gotten from your web hosting providers.
• If the server requires authentication, then add the following lines.
• auth_username = [email protected]
• auth_password = example_password
• Save the new changes.
• Restart Apache server.
Let’s now look at an example that sends a simple mail.
<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>
FILE UPLOADING
ERROR HANDLING
PHP and Database Connection
Basic database concepts
How to Create a MySQL Database with
phpMyAdmin
⚫ Make sure you have phpMyAdmin Installed. This
guide assumes you have phpMyAdmin installed and ready to
use.
⚫ Go to your phpMyAdmin homepage. For this guide
you need to navigate to the phpMyAdmin homepage. It can
usually be found under these directories, depending on your
server setup.http://localhost:8888/phpMyAdmin/
⚫ http://localhost/phpmyadmin
⚫ http://{your-ip-address}/phpmyadmin/
⚫ Login to your phpMyAdmin Page. Make sure you are
logged in to phpMyAdmin.
⚫ Enter your database name. Enter the name you want to
call your new database, here we have named it
"my_new_database".
⚫ Click "Create" and then you're done!
MySQL Database
⚫ With PHP, you can connect to and manipulate databases.
⚫ MySQL is the most popular database system used with PHP.
⚫ The data in a MySQL database are stored in tables. A table is a
collection of related data, and it consists of columns and rows.
⚫ MySQL is a database system used on the web
⚫ MySQL is a database system that runs on a server
⚫ MySQL is ideal for both small and large applications MySQL is very
fast, reliable, and easy to use
⚫ MySQL uses standard SQL
⚫ MySQL compiles on a number of platforms
⚫ MySQL is free to download and use
⚫ MySQL is developed, distributed, and supported by Oracle
Corporation
Connecting to MySQL Server
⚫ Before we can access data in the MySQL database, we need to be able to connect to
the server:
⚫ The process to connect MySQL server is given below:
<?php
$user = 'root';
$pass = '';
// Create connection
$conn = mysqli_connect('localhost', $user, $pass);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
else
{
echo "Connected successfully";
}
?>
Create a MySQL Database
⚫ The CREATE DATABASE statement is used to create a database in MySQL.
⚫ The following examples create a database named “nawaraj":
<?php
$user = 'root';
$pass = '';
$conn = mysqli_connect('localhost', $user, $pass);
// Check connection
//Create database
$sql = "CREATE DATABASE cct1";
if (mysqli_query($conn, $sql)) {
echo "Database created successfullyyy";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>
Create MySQL Tables
⚫ A database table has its own unique name and consists of columns
and rows.
⚫ The CREATE TABLE statement is used to create a table in
MySQL.
⚫ We will create a table named “contacts", with five columns: "id",
"firstName", "lastName", "email" :
⚫ CREATE TABLE contacts (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY
KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
)
Create table
<?php
$server = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "n1";
$conn = mysqli_connect($server, $dbuser, $dbpass,$dbname);
$sqlQuery = "CREATE TABLE contacts (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstName VARCHAR(35) NOT NULL,
lastName VARCHAR(35) NOT NULL,
email VARCHAR(55)
)";
?>
Insert Data Into MySQL
⚫ After a database and a table have been created, we can start
adding data in them.
⚫ 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,...)
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
⚫ Example to insert single record into a table
<?php
$user = 'root';
$pass = '';
$dbname = "n1";
// Create connection
$conn = mysqli_connect('localhost', $user, $pass, $dbname);
$sql = "INSERT INTO contacts (id,firstName, lastName, email)
VALUES (' ', 'John', 'Doe', '[email protected]')";
?>
⚫ Example to insert multiple record into a
table
<?php
$user = 'root';
$pass = '';
$dbname = "nabraj";
// Create connection
$conn = mysqli_connect('localhost', $user, $pass, $dbname);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Nabraj', 'Koirala', '[email protected]'),
('Apil', 'Koirala', '[email protected]'),
('Ram', 'Pandey', '[email protected]')";
?>
Select Data From a MySQL Database
⚫ 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 of Select Data From a MySQL Database
<?php
$user = 'root';
$pass = '';
$dbname = "n1";
// Create connection
$conn = mysqli_connect('localhost', $user, $pass, $dbname);
$sql = "SELECT * FROM contacts";
$result = mysqli_query($conn, $sql);
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstName"]. " " . $row["lastName"]
." Email:".$row["email"]."<br>";
}
?>
</body>
</html>
⚫ Select particular data from table
<?php
$user = 'root';
$pass = '';
$dbname = "n1";
// Create connection
$conn = mysqli_connect('localhost', $user, $pass, $dbname);
$sql = "SELECT id, firstName, lastName FROM contacts";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstName"]. " " .
$row["lastName"] ."<br>";
}
?>
</body>
</html>
Delete Data From MySQL
<?php
$user = 'root';
$pass = '';
$dbname = "n1";
// Create connection
$conn = mysqli_connect('localhost', $user, $pass, $dbname);
// sql to update a record
$sql = "UPDATE contacts SET lastname='Koirala' WHERE id=4";
?>
⚫ Close the Connection
⚫ The connection will be closed automatically when the script ends.
To close the connection before, use the following:
⚫ MySQLi Object-Oriented:
⚫ $conn->close();
⚫ MySQLi Procedural:
⚫ mysqli_close($conn);
⚫ PDO:
⚫ $conn = null;
⚫ Opening Database Connection
⚫ PHP provides mysql_connect function to open a database
connection.This function takes five parameters and returns a
MySQL link identifier on success, or FALSE on failure.
⚫ Syntax
⚫ connection
mysql_connect(server,user,passwd,new_link,client_flag);
⚫ Closing Database Connection
⚫ Its simplest function mysql_close PHP provides to close a
database connection.This function takes connection resource
returned by mysql_connect function. It returns TRUE on
success or FALSE on failure.
⚫ Syntax
⚫ bool mysql_close ( resource $link_identifier );
Example
⚫ <?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' .mysql_error()); }
echo 'Connected successfully';
mysql_close($conn);
?>
Create MySQL Database Using PHP
⚫ Creating a Database
⚫ To create and delete a database you should have admin
privilege. Its very easy to create a new MySQL database. PHP
uses mysql_query function to create a MySQL database.
This function takes two parameters and returns TRUE on
success or FALSE on failure.
⚫ Syntax
⚫ bool mysql_query( sql, connection );
⚫ Selecting a Database
⚫ Once you establish a connection with a database server then
it is required to select a particular database where your all
the tables are associated.
⚫ PHP provides function mysql_select_db to select a
database.It returns TRUE on success or FALSE on failure.
⚫ Syntax
⚫ bool mysql_select_db( db_name, connection );
⚫ Creating Database Tables
⚫ To create tables in the new database you need to do the same
thing as creating the database. First create the SQL query to
create the tables then execute the query using mysql_query()
function.
⚫ n case you need to create many tables then its better to create
a text file first and put all the SQL commands in that text file
and then load that file into $sql variable and excute those
commands.
⚫ Consider the following content in sql_query.txt file
⚫ CREATE TABLE employee( emp_id INT NOT NULL
AUTO_INCREMENT, emp_name VARCHAR(20) NOT
NULL, emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL, join_date timestamp(14) NOT
NULL, primary key ( emp_id ));
Deleting MySQL Database Using
PHP
⚫ Deleting a Database
⚫ If a database is no longer required then it can be deleted
forever.You can use pass an SQL command
to mysql_query to delete a database.
⚫ Example
⚫ Try out following example to drop a database.
⚫ Deleting a Table
⚫ Its again a matter of issuing one SQL command
through mysql_query function to delete any database table.
But be very careful while using this command because by
doing so you can delete some important information you
have in your table.
⚫ Example
⚫ Try out following example to drop a table −
Insert Data into MySQL Database
🞂 Maintenance Mode
🞂 Sometimes you may need to update some configuration
values or perform maintenance on your website. In such
cases, keeping it in maintenance mode, makes it easier
for you. Such web applications which are kept in
maintenance mode, throw an exception
namely MaintenanceModeException with a status
code of 503.
🞂 You can enable the maintenance mode on your Laravel
web application using the following command −
🞂 php artisan down
🞂 Once you finish working on updates and other
maintenance, you can disable the maintenance mode on
your web application using following command −
🞂 php artisan up p
Laravel - Routing
🞂 In the MVC framework, the letter ‘C’ stands for Controller. It acts as a
directing traffic between Views and Models
🞂 Creating a Controller
🞂 Open the command prompt or terminal based on the operating system
you are using and type the following command to create controller using
the Artisan CLI (Command Line Interface).
🞂 php artisan make:controller <controller-name> --plain Replace the
<controller-name> with the name of your controller.This will create a plain
constructor as we are passing the argument — plain. If you don’t want to
create a plain constructor, you can simply ignore the argument.The created
constructor can be seen at app/Http/Controllers.
🞂 You will see that some basic coding has already been done for you and you
can add your custom coding.The created controller can be called from
routes.php by the following syntax.
🞂 Syntax
🞂 Route::get(‘base URI’,’controller@method’);
🞂 Example
🞂 Step 1 − Execute the following command to
create UserController.
🞂 php artisan make:controller UserController --plainStep
2 − After successful execution, you will receive the
following output.
🞂 Step 3 − You can see the created controller
at app/Http/Controller/UserController.php with
some basic coding already written for you and you can
add your own coding based on your need.
Laravel - Views
🞂 Laravel Databases
🞂 Database interaction in laravel is easy among all other
server side scripting framework with variery of database
backends either SQL, query builder or eloquent ORM.
🞂 Various DB supported by laravel are:
🞂 MySQL 5.6+
🞂 PostgreSQL 9.4+
🞂 SQLite 3.8.8+
🞂 SQL Server 2017+
🞂 Configuration of DB in Laravel
🞂 The directory having database connections are located
inside config folder.
🞂 config/database.php
🞂 All DB connections are defined and default connections
can be set. Laravel uses Laravel Homestead virtual
machine for development on localmachine which can be
modified according to local database.
🞂 SQLite Configuration:
🞂 A SQLite DB can be created with the command touch
🞂 database/database.sqlite
🞂 And can be configured by setting up by using database
absolute path:
🞂 DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
🞂 Multiple DB Connections:
🞂 Laravel supports multiple database connections and
handle easily with connection() method on DB facade.
Connections can be accessed in such a way as shown
below:
🞂 $users = DB::connection('DIFF_DB')->select(...);
🞂 Make sure the name passed in connection method should
correspond to connection listed
in config/database.php file. PDO instance can also be
used on the connection instance by syntax shown below
by using getPdo() method:
🞂 $pdo = DB::connection()->getPdo();
🞂 Running RAW SQL Queries
🞂 After DB configuration you may simply run queries as
used in php using DB facade which provides method for
each type of query: select, insert, update, delete and other
statements. Below shown example and screenshot of
the select query and other queries will work in the same
manner.
Make UserController.php file and paste the
following code:
🞂 n web.php file add code metioned below:
🞂 Route::get('/database','UserController@index');
🞂 You must create a users DB in
your phpmyadminpannel.
🞂 Above query the select() method consist of two
parameters: select query and other is parameter binding
that is to be bound with query. Instead of using ? in above
query named binding can be used as shown below:
🞂 $results = DB::select('select * from users where id = :id',
['id' => 1]);
🞂 Insert Query:
🞂 DB::insert('insert into users (id, name) values (?, ?)', [2,
'Believ Master']);
🞂 Update Query:
🞂 $update = DB::update("update users set name =
'PHPTPOINT' where id = ?", [1]);
🞂 Delete Query:
🞂 $delete = DB::delete('delete from users');
🞂 Drop Query:
🞂 DB::statement('drop table users');