Unit-7 Web Technology
Unit-7 Web Technology
Unit-7
Database Connectivity in PHP
Introduction to SQL
Structured Query Language (SQL) is a standard query language that is used to work with relational
databases.
We use SQL to create databases, create tables in a database, read data from a table, insert data
in a table, update data in a table, delete data from a table, delete database tables, delete
databases and many more database operations. All the RDBMS like MySQL, Informix, Oracle, MS
Access and SQL Server use SQL as their standard database language. SQL allows users to query
the database in a number of ways, using English-like statements. Structure query language is not
case sensitive. Generally, keywords of SQL are written in uppercase.
Example
SELECT * FROM Customers;
CRUD is an acronym for CREATE, READ(SELECT), UPDATE, and DELETE statements in SQL. CRUD operations
act as the foundation of any computer programming language or technology.
1. Create:
In CRUD operations, 'C' is an acronym for create, which means to add or insert data into the SQL
table. So, firstly we will create a table using CREATE command and then we will use the INSERT
INTO command to insert rows in the created table.
Syntax for table creation:
CREATE TABLE Table_Name (ColumnName1 Datatype, ColumnName2 Datatype,...,
ColumnNameN Datatype);
Syntax for insertion of data in table:
INSERT INTO Table_Name (ColumnName1,...., ColumnNameN) VALUES (Value 1,....,Value
N),....., (Value 1,....,Value N);
Example:
CREATE TABLE employee(ID INT PRIMARY KEY, First_Name VARCHAR(20), Last_Name
VARCHAR(20), Salary INT, Email_Id VARCHAR(40));
INSERT INTO employee(ID, First_Name, Last_Name, Salary, Email_Id) VALUES(1, "Ram",
"Tamang", 59000, "[email protected]"), (2, "Sushma", "Singh", 62000,
"[email protected]"), (3, "Kavita", "Rai", 27000, "[email protected]");
Note: This will insert 3 rows at once.
2. Read:
In CRUD operations, 'R' is an acronym for read, which means retrieving or fetching the data from
the SQL table. So, we will use the SELECT command to fetch the inserted records from the SQL
table. We can retrieve all the records from a table using an asterisk (*) in a SELECT query. There
is also an option of retrieving only those records which satisfy a particular condition by using the
WHERE clause in a SELECT query.
Syntax to fetch all the records:
SELECT *FROM TableName;
Syntax to fetch records according to the condition:
SELECT *FROM TableName WHERE CONDITION;
Example:
SELECT *FROM employee;
SELECT *FROM employee WHERE Salary > 35000;
3. Update:
In CRUD operations, 'U' is an acronym for the update, which means making updates to the
records present in the SQL tables. So, we will use the UPDATE command to make changes in
the data present in tables.
Syntax:
UPDATE Table_Name SET ColumnName = Value WHERE CONDITION;
Example
➢ UPDATE employee SET Last_Name = "Giri" WHERE ID = 6;
➢ UPDATE employee SET Salary = "35000", Email_Id= " [email protected] " WHERE ID
= 10;
4. Delete:
In CRUD operations, 'D' is an acronym for delete, which means removing or deleting the records
from the SQL tables. We can delete all the rows from the SQL tables using the DELETE query.
There is also an option to remove only the specific records that satisfy a particular condition by
using the WHERE clause in a DELETE query.
Syntax to delete all the records:
DELETE FROM TableName;
Syntax to delete records according to the condition:
DELETE FROM TableName WHERE CONDITION;
Example :
DELETE FROM employee WHERE Salary = 34000;
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The output could be something like this:
Welcome Ram
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
<html>
<body>
<form action="welcome.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Welcome.php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
The HTML <form> method Attribute is used to specify the HTTP method used to send data while
submitting the form. There are two kinds of HTTP methods, which are GET and POST. The method
attribute can be used with the <form> element.
Attribute Values:
GET: In the GET method, after the submission of the form, the form values will be visible in the
address bar of the new browser tab. It has a limited size of about 3000 characters. It is only useful
for non-secure data not for sensitive information.
POST: In the post method, after the submission of the form, the form values will not be visible in
the address bar of the new browser tab as it was visible in the GET method. It appends form data
inside the body of the HTTP request. It has no size limitation. This method does not support
bookmark the result
Syntax:
<form method="get|post">
Database connectivity
PHP has built-in functions that allow us to connect to our database server to store and retrieve
the data.
Create a connection
we can access our MariaDB database through a PHP script. This let's us read and write data to
our database directly from our website.
To connect our script to the MySQL databases we have 2 options.
➢ MySQLi extension.
➢ PDO.
MySQLi: MySQLi is an open-source relational database management system that is used on the
web. This database system is reliable for both small and large applications.
PDO: PHP Data Object is a PHP extension that defines a lightweight and consistent interface for
accessing a database in PHP. It is a set of PHP extensions that provide a core PDO class and
database-specific driver.
Using MySQLi:
We need to create 3 variables for $servername, $username and $password. Now we will connect
to the server using mysqli_connect.
<?php
echo "Welcome br>";
// Connecting to the Database
$servername = "localhost";
$username = "root";
$password = "";
// Create a connection
$conn = mysqli_connect($servername, $username, $password);
?>
MySQL functions
AVG()
This function is used to calculate the average value.
COUNT()
This function is used to count the number of rows returned.
MAX()
This function returns the maximum value.
MIN()
This function returns the minimum value.
SUM()
This function is used to calculate the sum of the values.
CURDATE()
The MYSQL CURDATE() is used to get the current days date.
SELECT CURDATE();
ABS()
The ABS() function of MySQL accepts an integer value as a parameter and returns the absolute
value for the given integer.
CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more
arguments.
<?php;
$con = mysqli_connect($serverName, $username, $password);
?>
<?php
mysqli_select_db($con,$database_name);
?>
• “mysqli_select_db(…)” is the database selection function that returns either true or false
• “$database_name” is the name of the database
• “$con” is the database connection resource variable.
• Insert
• Select
• Update
• delete
It has the following syntax.
<?php
mysqli_query($con,$query) ;
?>
<?php
mysqli_num_rows($result);
?>
<?php
mysqli_fetch_array($result);
?>
<?php
mysqli_close($con);
?>
(CRUD Operation)
<?php
$con = mysqli_connect("localhost","root","");
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
//Create database
mysqli_query($con,"create database School");
// Use Database
mysqli_select_db($con,"School");
//Create Table
mysqli_query($con,"create table user(id int primary key,email varchar(30),password
varchar(30))");
//Delete a row
if(mysqli_query($con,"delete from user where id=102"))
{
echo "Deleted!<br>";
}
<html>
<head><title>Login Form</title></head>
<body>
<form action="logindb.php" method="post">
<h1>Sign In</h1>
<p>Please fill in this form to create an account.</p>
<label for="email"><b>Email</b></label>
<input type="text" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" name="psw" required>
<input type="submit" name="submit">Sign In</button>
<input type="button">Cancel</button>
</form>
</body>
</html>
logindb.html
<?php
if(isset($_POST['submit']))
{
$email=$_POST['email'];
$pass=$_POST['psw'];
$con=mysqli_connect("localhost","root","","School");
if(!$con)
{
die("Unable to connect!");
}
else{
$sql="select * from user where email='$email' and password='$pass'";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_array($result)){
echo "Successfully verified email and password";
echo "<h1>Hello ".$row[2]."</h1>";
}
}
else{
echo "Username and password doesnot match";
}
}
}
?>
Session and Cookies
PHP Session
A session creates a file in a temporary directory on the server where registered session
variables and their values are stored. This data will be available to all pages on the site
during that visit.
A PHP session is easily started by making a call to the session_start() function.This function first
checks if a session is already started and if none is started then it starts one. It is recommended
to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
Cookies in PHP
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.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
Example
<?php
$cookie_name = "user";
$cookie_value = "John";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";