PHP and MySql

About PHP and MySql

What is PHP and MySql

PHP is an abbreviation for PHP: Hypertext Preprocessor. PHP is a server-side scripting language optimised for web development. It is open-source, which means you can download and use it free. It is extremely simple to learn and apply. The files in PHP are having the ".php" extension. Rasmus Lerdorf inspired the first version of PHP and contributed to subsequent versions. It is an interpreted language that does not require the use of a compiler. It is compatible with numerous databases, including Oracle, Microsoft SQL Server, MySQL, PostgreSQL, Sybase, and Informix. It is capable of hosting a content management system such as WordPress and can be used to restrict user access. It supports HTTP Basic, HTTP Digest, IMAP, FTP and other major protocols. PHP is also used to power websites such as facebook.com and yahoo.com. One of the primary reasons for this is that PHP can easily be embedded in HTML files and HTML codes can also be written in a PHP file. PHP differs from client-side languages such as HTML in that PHP code is executed on the server, whereas HTML code is directly rendered on the browser. PHP codes are executed on the server before being returned to the browser.

What we are going to learn in PHP and MySql


How to install PHP

We need to install XAMPP to get a local server to run PHP files

Install XAMPP from Here

Step-1:install and open XAMPP.


Step-2:Start the Apache Server.


Step-3:Open the folder where you install XAMPP, open htdocs and create a folder where you save your PHP files.


Step-4:Open the folder with VS code and install the PHP extension from extensions tab.


Step-5:Create a new file as index.php and type the code given in instruction.


Step-6:Type localhost in the chrome. You can find the htdocs folder opened in it.


Step-6:Open the folder where you have save your PHP file.



The Echo and var_dump Function

Echo

Echo is used to print the value in the browser window

<!DOCTYPE html> <html> <body> <?php $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo "<br>"; echo $y; ?> </body> </html> Var_dump

The var_dump() function returns data from one or more variables. The data contains the variable's type and value.

<!DOCTYPE html> <html> <body> <?php $a = 32; echo var_dump($a) . "<br>"; $b = "Hello world!"; echo var_dump($b) . "<br>"; $c = 32.5; echo var_dump($c) . "<br>"; $d = array("red", "green", "blue"); echo var_dump($d) . "<br>"; $e = array(32, "Hello world!", 32.5, array("red", "green", "blue")); echo var_dump($e) . "<br>"; echo var_dump($a, $b) . "<br>"; ?> </body> </html>

Variable and Data types

Variables can store various types of data, and different data types can perform various functions. PHP recognises the following data types:

String

A string is a sequence of characters, like "Hello world!".

<!DOCTYPE html> <html> <body> <?php $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo "<br>"; echo $y; ?> </body> </html> Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

<!DOCTYPE html> <html> <body> <?php $x = 5985; var_dump($x); ?> </body> </html> Float

A float (floating point number) is a number with a decimal point or a number in exponential form.

<!DOCTYPE html> <html> <body> <?php $x = 10.365; var_dump($x); ?> </body> </html> Boolean

A Boolean represents two possible states: TRUE or FALSE.

<!DOCTYPE html> <html> <body> <?php $x = true; $y = false; var_dump($x); var_dump($y); ?> </body> </html> Array

An array stores multiple values in one single variable.

<!DOCTYPE html> <html> <body> <?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?> </body> </html> NULL

Null is a special data type which can have only one value: NULL.

<!DOCTYPE html> <html> <body> <?php $x = "Hello world!"; $x = null; var_dump($x); ?> </body> </html>

Condition

If, else, else if

By using the ‘if’ statement a block of statements will be executed until the condition is true. If the condition is false, then the block of statements will not be executed. If we want to execute more than one condition, then we use ‘else’/’’else if’ statement with ‘if’.

      
<!DOCTYPE html> <html> <body> <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?> </body> </html> Switch

The switch statement is a type of conditional statement in JavaScript, which is used to perform one condition out of different conditions. This is an excellent choice for long, nested if/else statements. The switch statement is used to evaluate an expression. The expression's value is then compared to the values of each case in the structure. If a match is found, the associated block of code is executed.

<!DOCTYPE html> <html> <body> <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?> </body> </html>

Function

A PHP function is a piece of code that is designed to perform a specific task. When someone calls a function, it execute that task. The function keyword is followed by a name, followed by parentheses, to define a PHP function (). Letters, digits, underscores and dollar signs can be used in function names (same rules as variables). Parameter names separated by commas may be included in the parentheses. The function's code to be executed is enclosed in curly brackets {}

      
<!DOCTYPE html> <html> <body> <?php function writeMsg() { echo "Hello world!"; } writeMsg(); ?> </body> </html> Function With Argument <?php function familyName($fname, $year) { echo "$fname Refsnes. Born in $year <br>"; } familyName("Hege", "1975"); familyName("Stale", "1978"); familyName("Kai Jim", "1983"); ?> PHP Return Type Declarations <?php declare(strict_types=1); // strict requirement function addNumbers(float $a, float $b) : float { return $a + $b; } echo addNumbers(1.2, 5.2); ?>

Local and Global Variable

Global Variables

A variable declared outside a function has a global scope can only be access outside function

<!DOCTYPE html> <html> <body> <?php $x = 5; function myTest() { echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html> Local Variables

A variable declared within function has a local scope and can only be accessed within function

<!DOCTYPE html> <html> <body> <?php function myTest() { $x = 5; echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html>

Regular expressions - regEx

Regular expressions (regexes) are a sequence of characters that describe a special search pattern in the form of a text string. In the programming world, they are primarily used to match some loosely defined patterns in order to accomplish some relevant tasks. Regexes are sometimes thought of as a mini programming language with pattern notation that allows users to parse text strings. Because the exact sequence of characters is unpredictable in advance, the regex aids in retrieving the required strings based on a pattern definition. A regular expression is shorthand for describing a string pattern that matches a specific amount of text. As you may be aware, PHP is an open-source language that is commonly used for website development and it includes regular expression functions as an important tool. Many other programming languages, including PHP have their own implementation of regular expressions. This is also true for other applications, which have their own support for regexes with various syntaxes. Regexes are used on very large files and strings by many modern languages and tools. Let's look at some of the benefits and applications of regular expressions.

HP provides a variety of functions that allow you to use regular expressions. Some The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly used ones.

Function Description
preg_match() If the pattern was found in the string, 1 is returned; otherwise, 0 is returned.
preg_match_all() The number of times the pattern was found in the string, which may be 0 in some cases.
preg_replace() Returns a new string with the matched patterns replaced by another string.
preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern.

<?php $str = "Entering into web development"; $pattern = "/web/i"; echo preg_match($pattern, $str); ?> preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a string.

<?php $str = "The rain in SPAIN falls mainly on the plains."; $pattern = "/ain/i"; echo preg_match_all($pattern, $str); ?> preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another string.

<?php $str = "Enter into Web Development"; $pattern = "/Enter/i"; echo preg_replace($pattern, "Entering", $str); ?>

Cookies

A cookie is frequently used to recognise a user. A cookie is a small file that is placed on the user's computer by the server. The cookie will be sent each time to the same computer when it requests a page via browser. Cookie values can be created and retrieved using PHP.

A cookie is created with the setcookie() function.

<!DOCTYPE html> <?php $cookie_name = "cookie_1"; $cookie_value = "Web Development"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?> <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]; } ?> <p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p> </body> </html>

Session

When we use an application by opening it, make changes and then close it, a session is created. The computer recognises user. It knows when we have started and closed the application. However, there is an issue on the internet: the web server has no idea that who are you or what you have done because the HTTP address does not maintain state. Session variables address this issue by storing user data that can be used across multiple pages (e.g. username, favourite color, etc). Session variables are retained by default until the user closes the browser.

A session is started with the session_start() function.

<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> </body> </html> Destroying the session <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php session_unset(); session_destroy(); echo "All session variables are now removed, and the session is destroyed." ?> </body> </html>

Date and time

The PHP date() function formats a timestamp to a more readable date and time.

<!DOCTYPE html> <html> <body> <?php echo "Today is " . date("Y/m/d") . "<br>"; echo "Today is " . date("Y.m.d") . "<br>"; echo "Today is " . date("Y-m-d") . "<br>"; echo "Today is " . date("l"); ?> </body> </html> Date Formats:
      $today = date("F j, Y, g:i a");                 		// March 10, 2001, 5:16 pm

      $today = date("m.d.y");                         		// 03.10.01

      $today = date("j, n, Y");                       		// 10, 3, 2001

      $today = date("Ymd");                           		// 20010310

      $today = date('h-i-s, j-m-y, it is w Day');     	// 05-16-18, 10-03-01, 1631 1618 6Satpm01
           
      $today = date('\i\t \i\s \t\h\e jS \d\a\y.');   	// it is the 10th day.

      $today = date("D M j G:i:s T Y");               		// Sat Mar 10 17:16:18 MST 2001

      $today = date('H:m:s \m \i\s\ \m\o\n\t\h');  // 17:03:18 m is month

      $today = date("H:i:s");                         		// 17:16:18

      $today = date("Y-m-d H:i:s");               		// 2001-03-10 17:16:18 
      

Creating database

For creating database we need to activate database first. The database can be activated by starting MySql in XAMPP application.



Steps for Creating Database

Step-1:Open Admin panel on mySql by clicking on Admin button of MySql in XAMPP.


Step-2:Create a new database by clicking on New button in the left side of admin window and give the name of your database.


Step-3:Give the table name and select no. of column of table in the admin panel.


Step-4: Give details of the given table in the admin panel


Detail of table elements

(we will discussing only those element which are needed)

Name: Used to enter the name of the column of the table in the database.

Type: Used to enter the type of element to be entered in column of the table in the database.

Length/Values: Used to give the length of the element of the column in table tag.

AI: AI stand for auto increment. Used to give serial no. of elements of the table.


Connecting To Database

We must define three variables: $servername, $username, and $password. Now we'll use mysqli connect to connect to the server. We will also add an extra feature to the code that will terminate the programme with an error message if the connection is not established. We'll use the die feature for this.

<?php echo "Welcome to the stage where we are ready to get connected to a database <br>"; $servername = "localhost"; $username = "root"; $password = ""; $conn = mysqli_connect($servername, $username, $password); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ echo "Connection was successful"; } ?>

Mysqli: MySQLi is a web-based open-source relational database management system. This database system is dependable for small and large applications alike.

Creating Database via PHP

<?php $servername = "localhost"; $username = "root"; $password = ""; $conn = mysqli_connect($servername, $username, $password); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ echo "Connection was successful<br>"; } $sql = "CREATE DATABASE divyanshdb"; $result = mysqli_query($conn, $sql); if($result){ echo "The db was created successfully!<br>"; } else{ echo "The db was not created successfully because of this error ---> ". mysqli_error($conn); } ?> Creating Table via PHP <?php $servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb"; $conn = mysqli_connect($servername, $username, $password, $database); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ echo "Connection was successful<br>"; } $sql = "CREATE TABLE `abc` ( `sno` INT(6) NOT NULL AUTO_INCREMENT , `name` VARCHAR(12) NOT NULL , `dest` VARCHAR(6) NOT NULL , PRIMARY KEY (`sno`))"; $result = mysqli_query($conn, $sql); if($result){ echo "The table was created successfully!<br>"; } else{ echo "The table was not created successfully because of this error ---> ". mysqli_error($conn); } ?> How to get this query?
        $sql = "CREATE TABLE `abc` ( `sno` INT(6) NOT NULL AUTO_INCREMENT , `name` VARCHAR(12) NOT NULL , `dest` VARCHAR(6) NOT NULL , PRIMARY KEY (`sno`))";

Step-1:open phpmyadmin and click on create new table.


Step-2:Fill the data in the table you have created.


Step-3:click on preview SQL. You can see the sql query to create the table with the given data.



Getting data using form

Step-1:Create a table in the database.


Step-2:Create a form using html and CSS.

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Contact Us</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Get/Post</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/cwhphp/21_Get_Post.php">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="container mt-3"> <h1>Contact us for your concerns</h1> <form action="" method="post"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="desc">Description</label> <textarea class="form-control" name="desc" id="desc" cols="30" rows="10"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html>



Step-3:Create a PHP script named as form.php to store data into form.

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $name = $_POST['name']; $email = $_POST['email']; $desc = $_POST['desc']; $servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb"; $conn = mysqli_connect($servername, $username, $password, $database); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ $sql = "INSERT INTO `contact` (`Name`, `Email`, `Description`, `time`) VALUES ('$name', '$email', '$desc', current_timestamp())"; $result = mysqli_query($conn, $sql); if($result){ echo 'Thankyou'; } else{ echo 'Error'; } } }

Step-4:update form action as: form action=”form.php”


Step-5:You can see that the page is working successfully.


Step-6:Now check the database.


Learning about form.php file
if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $name = $_POST['name']; $email = $_POST['email']; $desc = $_POST['desc'];

In this we are creating a custom post method and connecting the variable created in the php with the name of the input type of the forms

$servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb";

Now we are connecting with the database

$sql = "INSERT INTO `contact` (`Name`, `Email`, `Description`, `time`) VALUES ('$name', '$email', '$desc', current_timestamp())"; $result = mysqli_query($conn, $sql); if($result){ echo 'Thankyou'; } else{ echo 'Error'; }

This is the main logic to get the data into the table. The sql query is used to add data from the element to the database. If the connection was successful then the ‘Thank you’ message was appeared otherwise ‘Error’ message will be displayed. You can also customize the ‘Thank you” with the javascript popup or can redirect to other custom designed html pages.


CRUD Operations

The acronym CRUD stands for Create, Read, Update and Delete in computer programming. These are the four fundamental features of persistent storage. Furthermore, each letter in the acronym can refer to any function in relational database applications that is mapped to a standard HTTP method, SQL statement, or DDS operation. It can also refer to user-interface conventions that allow for the viewing, searching, and modification of data via computer-based forms and reports. Entities are read, created, updated, and deleted. Those same entities can be modified by retrieving data from a service and altering the setting properties before returning the data to the service for an update. Furthermore, CRUD is data-driven and makes use of HTTP action verbs in a consistent manner.

Create(insert)

Step1: Create a form as index.php

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Contact Us</title> </head> <body> <div class="container mt-3"> <h1>Contact us for your concerns</h1> <form action="insert.php" method="post"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="desc">Description</label> <textarea class="form-control" name="desc" id="desc" cols="30" rows="10"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html>

Step2: Create a file as insert.php to insert data

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $name = $_POST['name']; $email = $_POST['email']; $desc = $_POST['desc']; $servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb"; $conn = mysqli_connect($servername, $username, $password, $database); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ $sql = "INSERT INTO `contact` (`Name`, `Email`, `Description`, `time`) VALUES ('$name', '$email', '$desc', current_timestamp())"; $result = mysqli_query($conn, $sql); if($result){ echo 'Thankyou'; } else{ echo 'Error'; } }

Step3: Enter data and check the database


Retrieve(read)

Step1: Create a new file as select.php with the files created during insert

<?php $servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb"; $conn = mysqli_connect($servername, $username, $password, $database); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ echo "Connection was successful<br>"; } $sql = "SELECT * FROM `contact`"; $result = mysqli_query($conn, $sql); $num = mysqli_num_rows($result); echo $num; echo " records found in the DataBase<br>"; if($num> 0){ while($row = mysqli_fetch_assoc($result)){ echo ". Hello ". $row['Name']; echo "<br>"; } } ?>

Step2: insert data in form.


Step3: Open Select.php and you can see the data in the table



Update

Step1: Create a new file as index.html for UI

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Contact Us</title> </head> <body> <div class="container mt-3"> <h1>Contact us for your concerns</h1> <form action="update.php" method="post"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp"> </div> <div class="form-group"> <label for="new">new</label> <input type="text" name="new" class="form-control" id="new"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html>

Step2: create a new file as update.php to make updates in the database

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $name = $_POST['name']; $email = $_POST['email']; $desc = $_POST['desc']; $new = $_POST['new']; $servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb"; $conn = mysqli_connect($servername, $username, $password, $database); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ echo "Connection was successful<br>"; } $sql = "SELECT * FROM `contact` WHERE `Name`='$name'"; $result = mysqli_query($conn, $sql); $num = mysqli_num_rows($result); echo $num . " records found in the DataBase<br>"; $no=1; if($num> 0){ while($row = mysqli_fetch_assoc($result)){ echo $no . ". Hello ". $row['Name']; echo "<br>"; $no = $no +1; } } $sql = "UPDATE `contact` SET `Name` = '$new' WHERE `Name` = '$name'"; $result = mysqli_query($conn, $sql); echo var_dump($result); $aff = mysqli_affected_rows($conn); echo "<br>Number of affected rows: $aff <br>"; if($result){ echo "We updated the record successfully"; } else{ echo "We could not update the record successfully"; }} ?>

Step3: Check the old value in the database using slect.php created before.


Step4: Update the value using the main page.


Step5: Check the new value in the database.



Delete

Step1: Create a new file as index.html for UI

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Contact Us</title> </head> <body> <div class="container mt-3"> <h1>Contact us for your concerns</h1> <form action="delete.php" method="post"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html>

Step2: create a new file as delete.php to make updates in the database.

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $name = $_POST['name']; $servername = "localhost"; $username = "root"; $password = ""; $database = "divyanshdb"; $conn = mysqli_connect($servername, $username, $password, $database); if (!$conn){ die("Sorry we failed to connect: ". mysqli_connect_error()); } else{ echo "Connection was successful<br>"; } $sql = "DELETE FROM `contact` WHERE `Name` = '$name'"; $result = mysqli_query($conn, $sql); $aff = mysqli_affected_rows($conn); echo "<br>Number of affected rows: $aff <br>"; if($result){ echo "Delete successfully"; } else{ $err = mysqli_error($conn); echo "Not Delete successfully due to this error --> $err"; } } ?>

Step3: Check the old value in the database using select.php created before.


Step4: Check the old value in the database using select.php created before.


Step5: Check the old value in the database using select.php created before.



Login and Signup

Step1: Create a new table using SQL Query


SQL Query for database table
    CREATE TABLE `register` (
  `ID` int(10) NOT NULL,
  `First_Name` varchar(100) NOT NULL,
  `Last_Name` varchar(100) NOT NULL,
  `Email` varchar(100) NOT NULL,
  `Password` int(100) NOT NULL,
  `File` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  

Step2: We need to create multiple fie for multiple outcome

database.php: For connecting database

register.php: For getting the values from the user

login.php : For getting the values from the user

loginProcess.php For login process to check valid user or not

home.php : For welcome page after login

logout.php : For logout from the application



database.php <?php $url='localhost'; $username='root'; $password=''; $conn=mysqli_connect($url,$username,$password,"divyanshdb"); if(!$conn){ die('Could not Connect My Sql:' .mysql_error()); } ?>a register.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <title>Welcome to Finance Portal</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="assests/css/style.css"> </head> <body> <div class="signup-form"> <form action="register_a.php" method="post" enctype="multipart/form-data"> <h2>Register</h2> <p class="hint-text">Create your account</p> <div class="form-group"> <div class="row"> <div class="col"><input type="text" class="form-control" name="first_name" placeholder="First Name" required="required"></div> <div class="col"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div> </div> </div> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="Email" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="pass" placeholder="Password" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="cpass" placeholder="Confirm Password" required="required"> </div> <div class="form-group"> <input type="file" name="file" required> <!-- <input type="submit" name="upload" value="Upload" class="btn"> --> </div> <div class="form-group"> <label class="form-check-label"><input type="checkbox" required="required"> I accept the <a href="#">Terms of Use</a> & <a href="#">Privacy Policy</a></label> </div> <div class="form-group"> <button type="submit" name="save" class="btn btn-success btn-lg btn-block">Register Now</button> </div> <div class="text-center">Already have an account? <a href="login.php">Sign in</a></div> </form> </div> </body> </html> Register_a.php <?php extract($_POST); include("database.php"); $sql=mysqli_query($conn,"SELECT * FROM register where Email='$email'"); if(mysqli_num_rows($sql)>0) { echo "Email Id Already Exists"; exit; } else(isset($_POST['save'])) { $file = rand(1000,100000)."-".$_FILES['file']['name']; $file_loc = $_FILES['file']['tmp_name']; $folder="upload/"; $new_file_name = strtolower($file); $final_file=str_replace(' ','-',$new_file_name); if(move_uploaded_file($file_loc,$folder.$final_file)) { $query="INSERT INTO register(First_Name, Last_Name, Email, Password, File ) VALUES ('$first_name', '$last_name', '$email', 'md5($pass)', '$final_file')"; $sql=mysqli_query($conn,$query)or die("Could Not Perform the Query"); header ("Location: login.php?status=success"); } else { echo "Error.Please try again"; } } ?> Login.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <title>Welcome to Finance Portal</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="assests/css/style.css"> </head> <body> <div class="signup-form"> <form action="loginProcess.php" method="post" enctype="multipart/form-data"> <h2>Login</h2> <p class="hint-text">Enter Login Details</p> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="Email" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="pass" placeholder="Password" required="required"> </div> <div class="form-group"> <button type="submit" name="save" class="btn btn-success btn-lg btn-block">Login</button> </div> <div class="text-center">Don't have an account? <a href="register.php">Register Here</a></div> </form> </div> </body> </html> loginProcess.php <?php session_start(); if(isset($_POST['save'])) { extract($_POST); include 'database.php'; $sql=mysqli_query($conn,"SELECT * FROM register where Email='$email' and Password='md5($pass)'"); $row = mysqli_fetch_array($sql); if(is_array($row)) { $_SESSION["ID"] = $row['ID']; $_SESSION["Email"]=$row['Email']; $_SESSION["First_Name"]=$row['First_Name']; $_SESSION["Last_Name"]=$row['Last_Name']; header("Location: home.php"); } else { echo "Invalid Email ID/Password"; } } ?> home.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <title>Welcome to Finance Portal</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="assests/css/style.css"> </head> <body> <div class="signup-form"> <form action="home.php" method="post" enctype="multipart/form-data"> <h2>Welcome</h2> <br> <img src="main.jpg" height="150" width="150" style="border-radius:50%;display:block;margin-left:auto;margin-right:auto;" /> <p class="hint-text"><br><b>Welcome Divyansh Sachdev</p> <div class="text-center">Want to Leave the Page? <br><a href="logout.php">Logout</a></div> </form> </div> </body> </html> logout.php <?php session_start(); unset($_SESSION["id"]); unset($_SESSION["name"]); header("Location:login.php"); ?> </div> <!-- Footer Start --> <div class="container-fluid bg-dark text-light footer pt-5 mt-5 wow fadeIn" data-wow-delay="0.1s" style="visibility: visible; animation-delay: 0.1s; animation-name: fadeIn;"> <div class="copyright"> <div class="row"> <div class="col-md-6 text-center text-md-start mb-3 mb-md-0"> © <a class="border-bottom" href="#">CodingNito</a>, All Right Reserved. Designed By <a class="border-bottom" href="https://upsstartitsolutions.icns.in">UpStart IT Solutions</a> </div> <div class="col-md-6 text-center text-md-end"> <div class="footer-menu"> <a href="index.html">Home</a> <a href="courses.html">Tutorials</a> <a href="team.html">Courses</a> <a href="contact.html">Contact</a> </div> </div> </div> </div> </div> <!-- Foot --> <!-- Back to Top --> <a href="#" class="btn btn-lg btn-primary btn-lg-square back-to-top"><i class="bi bi-arrow-up"></i></a> <!-- JavaScript Libraries --> </div><iframe id="netlify-identity-widget" title="Netlify identity widget" style="position: fixed; top: 0; left: 0; border: none; width: 100%; height: 100%; overflow: visible; background: transparent; display: none; z-index: 99; " src="about:blank"></iframe></body></html>