0% found this document useful (0 votes)
5 views14 pages

Unit-7 Web Technology

The document provides an overview of database connectivity in PHP using SQL, detailing CRUD operations (Create, Read, Update, Delete) and essential SQL commands. It explains how to create and manipulate databases and tables, as well as how to handle form data using PHP's $_GET and $_POST methods. Additionally, it discusses the use of MySQLi and PDO for database connections, along with examples of executing SQL queries and handling user authentication.
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)
5 views14 pages

Unit-7 Web Technology

The document provides an overview of database connectivity in PHP using SQL, detailing CRUD operations (Create, Read, Update, Delete) and essential SQL commands. It explains how to create and manipulate databases and tables, as well as how to handle form data using PHP's $_GET and $_POST methods. Additionally, it discusses the use of MySQLi and PDO for database connections, along with examples of executing SQL queries and handling user authentication.
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/ 14

Page |1

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;

Some of The Most Important SQL Commands

• SELECT - extracts data from a database


• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table

Basic SQL commands (CRUD)

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.

Jhalnath Chapagain | GM COLLEGE


Page |2

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;

Jhalnath Chapagain | GM COLLEGE


Page |3

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;

Jhalnath Chapagain | GM COLLEGE


Page |4

HTML forms and Methods


The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:

<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>

Jhalnath Chapagain | GM COLLEGE


Page |5

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.

Jhalnath Chapagain | GM COLLEGE


Page |6

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);

// Die if connection was not successful


if (!$conn){
die("Sorry we failed to connect: ". mysqli_connect_error());
}
else{
echo "Connection was successful";
}

?>

MySQL functions
AVG()
This function is used to calculate the average value.

SELECT AVG(Score) from MyPlayers;

COUNT()
This function is used to count the number of rows returned.

SELECT COUNT(*) from MyPlayers;

Jhalnath Chapagain | GM COLLEGE


Page |7

MAX()
This function returns the maximum value.

SELECT MAX(Score) from MyPlayers;

MIN()
This function returns the minimum value.

SELECT MIN(Score) from MyPlayers;

SUM()
This function is used to calculate the sum of the values.

SELECT SUM(Score) from MyPlayers;

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.

SELECT ABS(-55787); //output: 55787

CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more
arguments.

SELECT CONCAT('My', 'S', 'QL'); //output: MySQL

Jhalnath Chapagain | GM COLLEGE


Page |8

Some PHP inbuilt-functions for mysqli connection and manipulation


1. PHP mysqli_connect function
The PHP mysql connect function is used to connect to a MySQL database server.
It has the following syntax.

<?php;
$con = mysqli_connect($serverName, $username, $password);
?>

• “$con” is the database connection resource variable.


• “mysqli_connect(…)” is the function for php database connection
• “$serverName” is the name or IP address of the server hosting MySQL server.
• “$username” is a valid user name in MySQL server.
• “$password” is a valid password associated with a user name in MySQL server.
2. PHP mysqli_select_db function
The mysqli_select_db function is used to select a database.
It has the following syntax.

<?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.

3. PHP mysqli_query function


The mysqli_query function is used to execute SQL queries.The function can be used to execute
the following query types;

• Insert
• Select
• Update
• delete
It has the following syntax.

<?php
mysqli_query($con,$query) ;
?>

Jhalnath Chapagain | GM COLLEGE


Page |9

• “mysqli_query(…)” is the function that executes the SQL queries.


• “$query” is the SQL query to be executed

4. PHP mysqli_num_rows function


The mysqli_num_rows function is used to get the number of rows returned from a select query.
It has the following syntax.

<?php
mysqli_num_rows($result);
?>

• “mysqli_num_rows(…)” is the row count function


• “$result” is the mysqli_query result set

5. PHP mysqli_fetch_array function


The mysqli_fetch_array function is used fetch row arrays from a query result set.
It has the following syntax.

<?php
mysqli_fetch_array($result);
?>

• “mysqli_fetch_array(…)” is the function for fetching row arrays


• “$result” is the result returned by the mysqli_query function.

6. PHP mysqli_close function


The mysqli_close function is used to close an open database connection.
It has the following syntax.

<?php
mysqli_close($con);
?>

Jhalnath Chapagain | GM COLLEGE


P a g e | 10

• “mysqli_close(…)” is the PHP function


• “$con” is used to pass in the server connection resource

Executing DDL and DML queries using PHP

(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))");

//Insert data (2 rows)


mysqli_query($con,"insert into user values(101,'[email protected]','fPouIEL')");
mysqli_query($con,"insert into user values(102,'[email protected]','UiDJaVa')");

//Update table row


if(mysqli_query($con,"update user set password='CvPoIH' where id=101"))
{
echo "Updated!<br>";
}

//Delete a row
if(mysqli_query($con,"delete from user where id=102"))
{
echo "Deleted!<br>";
}

//Select data from table and display


if ($result = mysqli_query($con, "SELECT * FROM user")) {

Jhalnath Chapagain | GM COLLEGE


P a g e | 11

echo "Returned rows are: " . mysqli_num_rows($result);


while($row=mysqli_fetch_array($result))
{
echo "<br>".$row[0]. " ". $row[1];
}

// Free result set


mysqli_free_result($result);
}
mysqli_close($con);
?>

Login and Authentication


login.html

<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!");

Jhalnath Chapagain | GM COLLEGE


P a g e | 12

}
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;
}

Jhalnath Chapagain | GM COLLEGE


P a g e | 13

$msg = "You have visited this page ". $_SESSION['counter'];


$msg .= "in this session.";
?>

<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>";

Jhalnath Chapagain | GM COLLEGE


P a g e | 14

echo "Value is: " . $_COOKIE[$cookie_name];


}
?>
</body>
</html>

Jhalnath Chapagain | GM COLLEGE

You might also like