3.study Material For Section-I-Part-III - PHP N MYSQL
3.study Material For Section-I-Part-III - PHP N MYSQL
(Resource: www.w3schools.com)
PHP has been one of the oldest and most used scripting languages for server-side development,
and it’s powering over more than 42 million sites today on the World Wide Web, according to
SimilarTech. PHP has certainly grown so much and matured over the course of 25 years, and
the latest major release, PHP7 brought along many enhancements to the performance,
boosting speed to up to 100% of that of PHP 5 and lowering the memory usage.
JavaScript - Node.js - is currently the hottest technology in web development; it’s a run-time
environment for JavaScript on the server side, simply put, it allows JavaScript to be used for
server-side development. The node community is growing very fast, and the node package
manager (NPM) boasts the highest amount of packages with 650,000+ packages available for
you to build your applications.
JAVA - frameworks use Java for server-side development like Spring and JEE.
Go- Go is a rich compiled programming language built by Google, and is said to be even simpler
than Python. It’s a concurrent programming language and since its compiled as well, this
contributes to making it a speedy language for web development.
Erlang - is one of the most powerful options on this list. It’s a concurrent functional
programming language that was designed specifically to handle the massive amount of traffic in
real-time applications. It’s certainly ideal for building REST API on your backend.
C++ - The most famous frameworks are WT and Crow, which is C++’s version of Flask, a mini
web framework.
Rust - is a popular language and a very beloved one, we ought to mention that you can develop
web applications.
Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
What is PHP?
PHP is a open source server side scripting language, and a powerful tool for making dynamic
and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
PHP code is executed on the server, and the result is returned to the browser as plain HTML
PHP can create, open, read, write, delete, and close files on the server
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash
movies. You can also output any text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
<?php
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
PHP Comments
<?php
// This is a single-line comment
<?php
/*
This is a multiple-lines comment block
that spans over multiple lines
*/
?>
<?php
echo "This ", "string ", "was ", "made ", "with multiple parameters."; ?>
But
<?php
print "This ", "string ", "was ", "made ", "with multiple parameters.";
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:
<?php
$x = 5; // global scope
function myTest() {
myTest();
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
myTest();
myTest();
myTest();
?>
String
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Integer
<?php
$x = 5985;
var_dump($x);
?>
Float
<?php
$x = 10.365;
var_dump($x);
?>
Boolean
$x = true;
$y = false;
-------------------------------------------------------
Array
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Class
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello
Dolly!
?>
Richness of PHP
Function Description
This function can be used to prepare a string for storage in a database and
database queries.
<?php
$str = bin2hex("Hello World!"); //48656c6c6f20576f726c6421
echo($str);
?>
<?php
$str = crc32("Hello World!"); //472456355
printf("%u\n",$str);
?>
crypt() One-way string hashing
The crypt() function returns a hashed string using DES, Blowfish, or MD5
algorithms.
<?php
echo levenshtein("Hello World","ello World");
echo "<br>";
echo levenshtein("Hello World","ello World",10,20,30);
?>
localeconv() Returns locale numeric and monetary formatting
information
For localization
<?php
$str = "Hello";
echo md5($str); //8b1a9953c4611296a827abf8c47804d7
?>
<?php
$filename = "test.txt";
$md5file = md5_file($filename);
echo $md5file;
?>
metaphone() Calculates the metaphone key of a string
<?php
$str = "Hello";
echo sha1($str); //f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0
?>
Type Casting:
(int), (integer), or intval()
PHP Constants
To create a constant, use the define() function.
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
== Identical $x === $y Returns true if
= $x is equal to $y,
and they are of
the same type
PHP Arrays
Indexed Array
Associative Array
Multidimensional Array
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
PHP - Sort Functions For Arrays
In this chapter, we will go through the following PHP array sort functions:
------------------------------------------------------------------------
PHP Global Variables - 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.
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
$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;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF']; o/p- /demo/demo_global_server.php
echo "<br>";
echo $_SERVER['SERVER_NAME']; - 35.194.26.41
echo "<br>";
echo $_SERVER['HTTP_HOST']; -35.194.26.41
echo "<br>";
echo $_SERVER['HTTP_REFERER']; -https://tryphp.w3schools.com/showphp.php?
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT']; - AppleWebKit/537.36 (KHTML, like Gecko)
echo "<br>";
echo $_SERVER['SCRIPT_NAME']; -/demo/demo_global_server.php
?>
Apache/2.4.34 (Win32)
$_SERVER['SERVER_SIGNATURE'] Returns the server version OpenSSL/1.0.2o PHP/5.6.38
and virtual host name
which are added to server-
Server at localhost Port 80
generated pages
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable communications
between clients and servers.
Example: A client (browser) sends an HTTP request to the server; then the
server returns a response to the client. The response contains status
information about the request and may also contain the requested content.
HTTP Methods
GET
POST
PUT
HEAD
DELETE
PATCH
OPTIONS
The two most common HTTP methods are: GET and POST.
Note that the query string (name/value pairs) is sent in the URL of a GET
request:
/test/demo_form.php?name1=value1&name2=value2
The data sent to the server with POST is stored in the request body of the HTTP request:
Comparison Chart
GET POST
placed inside
bookmarked.
plaintext
minimum as possible.
in URL.
cached.
PHP $_REQUEST
PHP $_REQUEST is a PHP super Global variable which is used to collect data
after submitting an HTML 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;
}
}
?>
PHP $_POST
$_POST is an array of variables passed to the current script via the HTTP POST
method.
PHP $_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.
<html>
<body>
<input type="submit">
</form>
</body>
</html>
collect.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['fname'];
$mname = $_POST['mname'];
$lname = $_POST['lname'];
?>
</body>
</html>
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data
after submitting an HTML form with method="get".
$_GET is an array of variables passed to the current script via the URL parameters.
<?php
if( $_GET["name"] || $_GET["email"] ) {
if (preg_match("/[^A-Za-z'-]/",$_GET['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_GET['name']."<br />";
echo "You mail id is". $_GET['email']. "<br />";
exit();
}
?>
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.
For Security
1. Strip unnecessary characters (extra space, tab, newline) from the user input data
(with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes()
function)
3. Use htmlspecialchars() function converts special characters to HTML entities. This
means that it will replace HTML characters like < and > with < and >. This
prevents attackers from exploiting the code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
?>
$exp = "/w3schools/i";
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which
may also be 0
preg_replace() Returns a new string where matched patterns have been replaced with
another string
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
Expression Description
[abc] Find one character from the options between the brackets
Metacharacter Description
| Find a match for any one of the patterns separated by | as in:
cat|dog|fish
\d Find a digit
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifier Description
Echo(“l”);
echo date("Y/m/d");
echo date("Y.m.d");
echo date("Y-m-d");
?>
<html>
<body>
readfile() Function
echo readfile("webdictionary.txt");
or
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
End-Of-File - feof()
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
PHP File Upload
n your "php.ini" file, search for the file_uploads directive, and set it to
On:
file_uploads = On
<!DOCTYPE html>
<html>
<body>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
What is a Cookie?
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.
setcookie(name, value, expire, path, domain, secure, httponly);
<?php
$cookie_name = "user";
$cookie_value = "alia bhat";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400
= 1 day
?>
<html>
<body>
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
</body>
</html>
MySQL Database
What is MySQL?
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
?>
Create a MySQL Database Using MySQLi (Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Create a MySQL Table Using MySQLi
CREATE TABLE Personalinfo (
grno INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Grno: " . $row["grno"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. row["email"]."<br>";
}
} else {
echo "0 results";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
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
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value