0% found this document useful (0 votes)
21 views96 pages

Unit 3&4

The document outlines the syllabus for a Web Technology course focusing on server-side scripting with PHP and MySQL. It covers PHP features, syntax, variables, data types, operators, control structures, and arrays, as well as how to connect PHP with MySQL for database operations. The course aims to provide students with the skills to create dynamic web applications using PHP and manage data with MySQL.
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)
21 views96 pages

Unit 3&4

The document outlines the syllabus for a Web Technology course focusing on server-side scripting with PHP and MySQL. It covers PHP features, syntax, variables, data types, operators, control structures, and arrays, as well as how to connect PHP with MySQL for database operations. The course aims to provide students with the skills to create dynamic web applications using PHP and manage data with MySQL.
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/ 96

Web Technology

(CSE 208 )

( 1I/4 B.Tech-CSE)
Unit- III

SIKHINAM NAGAMANI, ASSISTANT PROFESSOR


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SRM UNIVERSITY AP
1
Syllabus

Introduction to Server-side scripting-Overview of


PHP-Features of PHP-Primitives, operations and
expressions-Control statements and arrays in PHP-Functions
and pattern matching in PHP-Form handling-Cookies,
sessions, filters in PHP-Object oriented programming using
PHP-Overview of other popular server-side scripting
languages-Introduction to MySQL and features of
MySQL-Connect MySQL with PHP-Querying a MySQL
database with PHP-Various operations on MySQL database
2
Introduction to Server-side scripting

Makes the static pages dynamic by interacting with the


database.
Provide the client with data that doesn’tresideat the
client.
Behave differently for different users.
Provides improved security measures, since we can code
things that can never be viewed from the browser.
Avoids browser compatibility problems.
Processing the form’s data (submitted by the user).
3
Overview of PHP

The acronym PHP means Hypertext Preprocessor


developed in 1995 by Rasmus Lerdorf (member of the
Apache Group)
originally designed as a tool for tracking visitors at
Lerdorf's Web site
developed into full-featured, scripting language for
server-side programming
free, open-source
server plug-ins exist for various servers
4
Overview of PHP

❑ Overview of PHP
PHP scripts are executed on the server
It is free to download and use It is powerful enough to be at the core of
the biggest blogging system on the web (WordPress)!
It is deep enough to run the largest social network (Facebook)!
It is also easy enough to be a beginner's first server side language!
Runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
Compatible with almost all servers used today (Apache, IIS, Wamp etc)
Supports a wide range of databases
Easy to learn and runs efficiently on the server side

5
Overview of PHP

❑ Overview of PHP
generate dynamic page content
create, open, read, write, delete, and close files on the server
collect form data
send and receive cookies
add, delete, modify data in your database
be used to control user-access
encrypt data
PHP Language is NOT Case Sensitive. For example, print & PRINT mean the
same. However, the variables are case sensitive. $num & $Num are treated as
different variables.
PHP is a Loosely Typed Language.
6
Overview of PHP
❑ PHP Scripts
■ PHP is server side scripting, very good for creating dynamic
content
■ Syntax based on Perl, Java, and C
■ Typically file ends in .php
?> tag
■ Separated in files with the <?php
■ php commands can make up an entire file, or can be contained
in html-
-this is a choice….
■ Program statements ends with semicolon ";"
7
Overview of PHP
❑ Creating & Running PHP
Script
PHP is a server-side scripting language. So, to run PHP scripts,
you need to install PHP and a. web-server software like Apache /
Wamp / Xamp. For scripting using databases, a DBMS such as
MySQL should be installed.
The most compatible options include PHP + Apache / Wamp +
MySQL
The PHP files (.php files) should be copied to a particular folder
(htdocs or html or www etc.) where the webpages need to be
hosted.
8
Overview of PHP

❑ Creating & Running PHP


Script
The basic syntax of a PHP code is as follows:
Syntax:
<?php
// PHP code goes here
?>
<HTML>
<BODY>
<?php
echo "Hello , World";
?>
</BODY>
</HTML>
9
Overview of PHP
❑ Parsing

We've talk about how the browser can read a text file and
process it, that's a basic parsing method

Parsing involves acting on relevant portions of a file and


ignoring others

Browsers parse web pages as they load

Web servers with server side technologies like php parse


web pages as they are being passed out to the browser

10
Overview of PHP
❑ Two Ways to parse PHP
■ You can embed sections of php inside html:

<html>
<body>
<?php
$myvar = "Hello World!";
echo $myvar;
?>
</body>
</html>

11
Overview of PHP

■ Or you can call html from php:

<?php
echo "<html><h1>SRM AP</h1></html>"
?>

■ Structurally similar to C/C++


■ Supports procedural and object-oriented paradigm (to some
degree)
■ All PHP statements end with a semi-colon
■ Each PHP script must be enclosed in the reserved PHP tag
12
Overview of PHP
❑ Comments in PHP
A comment in PHP code is a line that is not executed as a part of
the program. Its only purpose is to be read by someone who is
looking at the code.

<?php
// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */
?>

13
Overview of PHP
❑ PHP Variables

In PHP, a variable starts with the $ sign


A variable can have a short name (like $x and $y) or a more
descriptive name ($age, $carname, $total_volume).
❑ $x = 5555;
❑ Rules for PHP variables: ❑ $y = “Siva"

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 _ ) 14
Variable names are case-sensitive ($age and $AGE are two
Overview of PHP
❑ PHP Variables
■ Case-sensitive ($Foo != $foo != $fOo)
■ Global and locally-scoped variables
■ Global variables can be used anywhere
■ Local variables restricted to a function or class
■ Certain variable names reserved by PHP
■ Form variables ($_POST, $_GET)
■ Server variables ($_SERVER)
■ Etc.
15
Overview of PHP

❑ PHP echo and print Statements


With PHP, there are two basic ways to get
output: echo and print.
echo and print are more or less the same. They are both
used to output data to the screen.
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with
multiple parameters.";
?>
16
Overview of PHP
❑ PHP echo and print Statements

<?php
$txt1 = "Learn PHP";
$txt2 = “at SRM AP";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";


echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>

17
Overview of PHP
❑ PHP echo and print Statements
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello SRM AP!<br>";
print "I am CSE-C Student!";
?>
<?php
$txt1 = “Hello SRM";
$txt2 = “I am CSE-C Student";
$x = 49;
$y = 59;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
18
Overview of PHP
❑ Data Types

Data Type Example


String “Hello”
Integer 4 or –4
Double 4.005
Boolean TRUE (introduced in
PHP4)

Syntax for variable declaration:


$x = “Hello”; //$x is of type String

$y = 10; //$y is of type Integer


$z = 8.77; //$z is of type Double
19
Overview of PHP
❑ Data Types
<html>
<body>
<?php Output:
$x = "Hello world!"; string(12) "Hello world!"
$y = 'Hello world!’; string(12) "Hello world!“
$Z = 5; int(5)

var_dump($x);
echo "<br>";
var_dump($y);
echo "<br>";
var_dump($z);
?>

</body>
</html>
20
Overview of PHP

❑ PHP Constants
A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign


before the constant name).

To create a constant, use the define() function.

define(name, value,
case-insensitive);
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant
name should be case-insensitive. 21
Overview of PHP
❑ PHP Constants
<html>
<body>
<?php
// case-sensitive constant name
define("GREETING", "Welcome to SRM AP
CSE!");
echo GREETING;
?>
</body>
</html>
<?php
// case-insensitive constant name
define("GREETING", "Welcome to SRM AP
CSE!", true);
echo greeting;
?> 22
Overview of PHP
❑ Operators
■ Arithmetic Operators: +, -, *,/ , %, ++,
--
■ Assignment Operators: =, +=, -=, *=, /=,
%=
■ Comparison Operators: ==, !=, >, <, >=,
<=
■ Logical Operators: &&, ||, !
■ String Operators: . and .= (for string concatenation)

Example
Is the same as
x+=y x=x+y
x-=y x=x-y
x=x*y
x*=y x=x/y
x/=y x=x%y
x%=y 23
Overview of PHP
❑ Operators

$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";

24
Overview of PHP
❑ Operators Example

<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x + $y;
echo "<br>";
echo $x - $y;
?>

</body>
</html>
25
PHP Examples
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>This is going to be ignored by the PHP interpreter.</p>
<?php
echo "<p>While this is going to be parsed.</p>";
?>
<p>This will also be ignored by the PHP preprocessor.</p>
<?php
print("<p>Hello and welcome to <i>my</i> page!</p>");
?>
<?php
//This is a comment
?>
</body>
</html>
26
Overview of PHP

❑ PHP Conditional Statements / Control Structures


if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and
another code if that condition is false
if...elseif...else statement - executes different codes for more
than two conditions
switch statement - selects one of many blocks of code to be
executed

27
Overview of PHP

❑ PHP
while Loops
- loops through a block of code as long as the specified
condition is true
do...while - loops through a block of code once, and then
repeats the loop as long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an
The break statement can be used to jump out
array
of a for loop.
The continue statement stops the current iteration in
the for loop and continue with the next.

28
Overview of PHP

<html> <html>
<body> <body>

<?php <?php
for ($x = 0; $x < 10; $x++) { for ($x = 0; $x < 10; $x++) {
if ($x == 4) { if ($x == 4) {
continue; break;
} }
echo "The number is: $x echo "The number is: $x
<br>"; <br>";
} }
?> ?>

</body> </body>
</html> </html> 29
Overview of PHP
❑ PHP Arrays
An array is a special variable that can hold many values under a
single name, and you can access the values by referring to an
index number or name.
In PHP, there are three types of arrays:
•Indexed arrays - Arrays with a numeric index - In indexed arrays
each item has an index number.
•Associative arrays - Arrays with named keys - Associative arrays
are arrays that use named keys that you assign to them.
•Multidimensional arrays - Arrays containing one or more arrays
- 30
Overview of PHP
❑ Indexed arrays
<html>
<body>

<?php
$cars = array(“Siva", “Rama",
“Krishna");
echo $cars[0];
echo $cars[2];

?>

</body>
</html>
31
Overview of PHP
❑ Associative arrays

<html>
<body>

<?php
$car = array("brand"=>“BMW", "model"=>“Series7",
"year"=>2024);
echo $car["model"];
?>

</body>
</html>

32
Overview of PHP
❑ Multidimensional arrays
<html>
<body>
<?php
$student = array (
array("Siva",85,"A"),
array("Rama",80,"B"),
array("Krishna",90,"O"),
array("Pavan",85,"A")
);
echo $student[0][0].": Marks: ".$student[0][1].", Grade:
".$student[0][2].".<br>";
echo $student[1][0].": Marks: ".$student[1][1].", Grade:
".$student[1][2].".<br>";
echo $student[2][0].": Marks: ".$student[2][1].", Grade:
".$student[2][2].".<br>";
echo $student[3][0].": Marks: ".$student[3][1].", Grade:
".$student[3][2].".<br>"; 33
Overview of PHP
❑ PHP Array Functions
The count() function returns the number of elements in an
array.
The current() function returns the value of the current element
in an array.
The range() function creates an array containing a range of
elements.
The next() function moves the internal pointer to, and outputs,
the next element in the array.
The prev() function moves the internal pointer to, and outputs,
34
the previous element in the array.
Overview of PHP
PHP array sort functions:
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to
the value
• ksort() - sort associative arrays in ascending order, according to
the key
• arsort() - sort associative arrays in descending order, according
to the value
• krsort() - sort associative arrays in descending order, according
35
to the key
Overview of PHP

<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++)
echo $numbers[$x]." ";
echo "<br>";
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++)
echo $numbers[$x]." ";
?>
</body>
</html>
36
Overview of PHP
❑ Superglobals
Some predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do
anything special.

The PHP superglobal variables are: $GLOBALS, $_SERVER,


$_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE,
$_SESSION

37
Overview of PHP

❑ $GLOBALS
$GLOBALS is a PHP super global variable which is used to access
global variables from anywhere in the PHP script (also from within
functions or methods). PHP stores all global variables in an array
called $GLOBALS[index]. The index holds the name of the variable.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] +
$GLOBALS['y'];
}
addition();
echo $z;
?> 38
Overview of PHP
❑ $_SERVER
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.

39
Overview of PHP

<?php
echo
$_SERVER['PHP_SELF']."<br>";
echo
$_SERVER['SERVER_NAME']."<br
>";
echo
$_SERVER['HTTP_HOST']."<br>";
echo
$_SERVER['SERVER_SOFTWARE'
40
]."<br>";
Overview of PHP
❑ $_REQUEST
$_REQUEST is a PHP super global variable which is used to collect
data after submitting an HTML form.
This example below shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the form
data is sent to the file specified in the action attribute of the <form> tag.
In this example, we point to this file itself for processing form data. If
you wish to use another PHP file to process form data, replace that with
the filename of your choice. Then, we can use the super global variable
$_REQUEST to collect the value of the input field.

41
Overview of PHP

<form method="post" action="<?php echo


$_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"]
== "POST")
{
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name))
echo "Name is empty";
else
echo $name;
}
42
?>
Overview of PHP

❑ $_POST
$_POST is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="post".
$_POST is also widely used to pass variables.

This example below shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the
form data is sent to the file specified in the action attribute of the
<form> tag.

In this example, we point to the file itself for processing form data.
If you wish to use another PHP file to process form data, replace
that with the filename of your choice. Then, we can use the super
global variable $_POST to collect the value of the input field. 43
Overview of PHP

<?php
if
($_SERVER["REQUEST_METHOD"
] == "POST")
{
// collect value of input field
$name = $_POST['fname'];
if (empty($name))
echo "Name is empty";
else
echo $name;
}
?>
44
Overview of PHP
❑ $_GET

$_GET is a PHP super global variable which is used to collect form


data after submitting an HTML form with method="get". $_GET
can also collect data sent in the URL.

45
Overview of PHP

getmethodex.php:

<form action = "gettestex.php" method = "GET">


Firstname: <input type = "text" name =
"fname" /> <br>
Lastname: <input type = "text" name =
"lname" /> <br>
Branch: <input type = "text" name = "branch"
/> <br>
Section: <input type = "text" name = "section"
/> <br>
Year: <input type = "text" name = "year" />
<br>
CollegeName: <input type = "text" name =
"cname" /> <br> 46
Address: <input type = "text" name = "address"
Overview of PHP
❑ gettestex.php

47
Overview of PHP

48
Overview of PHP

❑ Functions
Built-in Functions : PHP has over 1000 built-in functions that can
be called directly, from within a script, to perform a specific task.

User Defined Functions: Besides the built-in PHP functions, it is


possible to create your own functions. A user-defined function
declaration starts with the word function:

Syntax
function functionName()
{
code to be executed;
}

**Function names are not case-sensitive.


49
Overview of PHP
❑ Example

<html>
<body>
<?php
function writeMsg()
{
echo “Welcome to SRM AP";
}
writeMsg();
?>
</body>
</html>

50
Overview of PHP
❑ Example

<?php
function Name($fname,
$year)
{
echo "$fname Born in
$year <br>";
}
Name("RAM","Treta
Yuga");
Name("Lakshman","Treta
Yuga");
?> 51
Overview of PHP
❑ Default Argument Value
The following example shows how to use a default parameter. If we
call the function setHeight() without arguments it takes the default
value as argument.
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight
<br>";
}
setHeight(350);
setHeight();
setHeight(80);
?>
52
Overview of PHP
❑ Using return statement:

<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) .
"<br>";
echo "7 + 13 = " . sum(7,13) .
"<br>";
echo "2 + 4 = " . sum(2,4);
?>

53
Overview of PHP
❑ Parameter passing to
Functions:
PHP allows us two ways in which an argument can be passed into a
function:
Pass by Value: On passing arguments using pass by value, the
value of the argument gets changed within a function, but the
original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.
Pass by Reference: On passing arguments as pass by reference,
the original value is passed. Therefore, the original value gets
altered. In pass by reference we actually pass the address of the
54
value, where it is stored using ampersand sign(&).
Overview of PHP
❑ Example

55
Overview of PHP
❑ Pattern matching in PHP

A regular expression is a sequence of characters that forms a


search pattern.
When you search for data in a text, you can use this search
pattern to describe what you are searching for.
A regular expression can be a single character, or a more
complicated pattern.
Regular expressions can be used to perform all types of text
search and text replace operations.
56
Overview of PHP
❑ Pattern matching in PHP

Function Description
preg_match Returns 1 if the pattern was found in the string and 0
() if not
preg_match Returns the number of times the pattern was found in
_all() the string, which may also be 0
preg_replac Returns a new string where matched patterns have
e() been replaced with another string

57
Overview of PHP

58
Overview of PHP

❑ Form Handling

The PHP superglobals $_GET and $_POST are used to collect


form-data.

59
Overview of PHP
❑ Example:

60
Overview of PHP
❑ Cookies:
A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie
too. With PHP, you can both create and retrieve cookie values. A
cookie is created with the setcookie() function.
Create/Retrieve a Cookie :
The following example creates a cookie named "user" with the
value "XYZ". The cookie will expire after 30 days (3600 * 30). The
"/" means that the cookie is available in entire website (otherwise,
select the directory you prefer). 61
Overview of PHP
❑ Cookies:

We then retrieve the value of the cookie "user" (using the global
variable $_COOKIE).
We also use the isset() function to find out if the cookie is set.
The setcookie() function must appear BEFORE the <html> tag.

62
Overview of PHP
❑ Cookie Creation:

63
Overview of PHP

❑ Modify a Cookie Value:

To modify a cookie, just set (again) the cookie using the


setcookie() function

64
Overview of PHP

65
Overview of PHP

❑ Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration
date in the past.

66
Overview of PHP
❑ Sessions
In general, session refers to a frame of communication between two
mediums. A PHP session is used to store data on a server rather
than the computer of the user. Session identifiers or SID is a
unique number which is used to identify every user in a session
based environment. The SID is used to link the user with his
information on the server like posts, emails etc.

A session is a way to store information (in variables) to be used


across multiple pages. Unlike a cookie, the information is not
67
stored on the user’s computer.
Overview of PHP
❑ Sessions

68
Overview of PHP
❑ Start a PHP Session

The first step is to start up a session. PHP session_start() function is


used to start the session. It starts a new or resumes existing session.
It returns existing session if session is created already. If session is
not available, it creates and returns new session. It creates a new
session ID for the user.

<?php
// Start the session
session_start();
?>
69
Overview of PHP
❑ Storing Session Data

Session variables are set with the PHP global variable:


$_SESSION. $_SESSION is an associative array that contains all
session variables. It is used to set and get session variable values.
The stored data can be accessed during lifetime of a session.

70
Overview of PHP

❑ Example: Let's create a new page called "demo_session1.php". In this page,


we start a new PHP session and set some session variables:

<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "XYZ";
echo "Session variables are set.";
?>
</body>
</html>
71
Overview of PHP

❑ Accessing Session Data: Data stored in sessions can be easily


accessed by firstly calling session_start() and then by passing
the corresponding key to the $_SESSION associative array.

❑ We create another page called "demo_session2.php". From this


page, we will access the session information we set on the first
page ("demo_session1.php"). Session variables are not passed
individually to each new page, instead they are retrieved from
the session we open at the beginning of each page
(session_start()).
72
Overview of PHP

<?php
session_start();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo 'The Name of the student is :' . $_SESSION["Name"] .
'<br>’;
echo 'The Roll number of the student is :' .
$_SESSION["Rollnumber"] . '<br>';
?>
</body>
</html>
73
Overview of PHP
❑ Destroying Session: To delete only a certain session data, the
unset feature can be used with the corresponding session variable
in the $_SESSION associative array.

74
Overview of PHP
<?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>
75
Overview of PHP

PHP Filters

PHP filters are used to validate and sanitize external input.

The PHP filter extension has many of the functions needed for
checking user input, and is designed to make data validation easier
and quicker.

The filter_list() function can be used to list what the PHP filter
extension offers:

76
Overview of PHP

<html> <table>
<head> <tr>
<style> <td>Filter Name</td>
table, th, td { <td>Filter ID</td>
border: 1px solid </tr>
black; <?php
border-collapse: foreach (filter_list() as $id
collapse; =>$filter) {
} echo '<tr><td>' . $filter .
th, td { '</td><td>' . filter_id($filter) .
padding: 5px; '</td></tr>';
} }
</style> ?>
</head> </table>
<body> 77
Overview of PHP
PHP filter_var() Function
The filter_var() function both validate and sanitize data.

The filter_var() function filters a single variable with a specified


filter. It takes two pieces of data:
<html>
<body>
The variable you want to check
The type of check to use <?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str,
FILTER_SANITIZE_STRING);
echo $newstr;
Output: ?>
Hello World!
</body>
</html> 78
Overview of PHP

Validate an Integer:
The following example uses the filter_var() function to check if the
variable $int is an integer. If $int is an integer, the output of the code
below will be: "Integer is valid". If $int is not an integer, the output
will be: "Integer is not valid":

79
Overview of PHP

<html>
<body>

<?php
$int = 100;

Output: if (!filter_var($int,
FILTER_VALIDATE_INT) === false) {
Integer is echo("Integer is valid");
} else {
valid echo("Integer is not valid");
}
?>

</body>
</html>

80
Overview of MySQL
❑ 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.

81
Overview of MySQL
❑ MySQL Database:
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
82
Overview of MySQL
❑ MySQL Database:
Database Queries:
A query is a question or a request.
We can query a database for specific information and have a
recordset returned.

Open a Connection to MySQL :


Before we can access data in the MySQL database, we need to be
able to connect to the server.

83
Overview of MySQL
❑ MySQL Database:

Close the Connection:


The connection will be closed automatically when the script ends. To close
the connection before, use the following:
mysqli_close($conn);
84
Overview of MySQL

❑ Create a MySQL Database


A database consists of one or more tables.
The CREATE DATABASE statement is used to create a
database in MySQL. The following example create a database
named "myDB".

85
Overview of MySQL
❑ MySQL Database:

86
Overview of MySQL
Create Table: The CREATE TABLE statement is used to create a
table in MySQL. We will create a table named "Employee", with
four columns: "id", "firstname", "lastname", "email".

87
Overview of MySQL
❑ Insert Data:
After a database and a table have been created, we can insert data
in the table.

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

88
Overview of MySQL
❑ Insert Data:

89
Overview of MySQL
Select Data:

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

90
Overview of MySQL
❑ Select Data:

91
Overview of MySQL
❑ MySQL Database:

WHERE Clause:

The WHERE clause is used to filter records. The WHERE clause is


used to extract only those records that fulfill a specified condition.

SELECT column_name(s) FROM table_name WHERE


column_name operator value

$sql = "SELECT id, firstname, lastname FROM Employee where


id=2047";

92
Overview of MySQL
❑ MySQL Database:

ORDER BY Clause :

The ORDER BY clause is used to sort the result-set in ascending


or descending order. The ORDER BY clause sorts the records in
ascending order by default. To sort the records in descending
order, use the DESC keyword.

SELECT column_name(s) FROM table_name ORDER BY


column_name(s) ASC|DESC

$sql = "SELECT id, firstname, lastname FROM Employee


ORDER BY firstname";
93
Overview of MySQL
❑ MySQL Database:

Delete Data :

The DELETE statement is used to delete records from a table:

DELETE FROM table_name WHERE some_column =


some_value

The WHERE clause specifies which record or records that should


be deleted. If you omit the WHERE clause, all records will be
deleted!

94
Overview of MySQL
❑ MySQL Database:
Update Data:

The UPDATE statement is used to update existing records in a


table:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

The WHERE clause specifies which record or records that should


be updated. If you omit the WHERE clause, all records will be
updated!
95
96

You might also like