Professional Documents
Culture Documents
(16SCCCA6P/16SCCCS6P)
LABORATORY MANUAL
Handled By
Mr.S.Boobalathandayuthapani
Mr.S.Tamilselvan
Register Number
Name
DECEMBER 2020
Year Semester
Instructor Name
3 Array Concepts
5 Designing a Webpage
7 File Operations
8 PHP Cookies
9 PHP Session
Array Concepts
Application to Find Minimum Value from an Array
Week3 Program to Change instead of Colon(:) to make like (@,#,%,&). 16
Program to Find Maximum Number from Multidimensional Array.
Designing a Webpage
Application to Generate Addition Table
Week5 Generate the Table for Subtraction and Division 26
Generate Multiplication table for the given numbers
File Operations
Application to List out the folders and files
Week7 Program to list out the files present in the given directory. 34
Program to download a file from the server
PHP Cookies
Cookies - Basic Programs
Week8 38
Program to show the “Last Visited” date and time of a webpage.
PHP Session
Session - Basic Programs
Week9 43
Program to show the number of views (Count) of a website.
Introduction to PHP
PHP scripts are executed on the server and the result is sent to the web
browser as plain HTML. PHP can be integrated with the number of popular
databases, including MySQL, PostgreSQL, Oracle, Microsoft SQL Server,
Sybase, and so on. The current major version of PHP is 8.
There are lots more things to do with PHP.
What is PHP
Easy to learn: PHP is easy to learn and use. For beginner programmers who
just started out in web development, PHP is often considered as the preferable
choice of language to learn.
Open source: PHP is an open-source project. It is developed and maintained by
a worldwide community of developers who make its source code freely available
to download and use.
Portability: PHP runs on various platforms such as Microsoft Windows, Linux,
Mac OS, etc. and it is compatible with almost all servers used today such Apache,
IIS, etc.
Fast Performance: Scripts written in PHP usually execute or runs faster than
those written in other scripting languages like ASP, Ruby, Python, Java, etc.
Vast Community: Since PHP is supported by the worldwide community, finding
help or documentation related to PHP online is extremely easy.
PHP Features
Web Development
PHP is widely used in web development now a day. PHP can develop
dynamic websites easily. But you must have the basic the knowledge of following
technologies for web development as well.
o HTML
o CSS
o JavaScript
o Ajax
o XML and JSON
o jQuery
PHP Installation
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that is given below:
If you are on Windows and don't want Perl and other features of XAMPP,
you should go for WAMP. In a similar way, you may use LAMP for Linux and
MAMP for Macintosh.
Week 1 Laboratory: To Understand the PHP usage and how to work with Initial and
learn to do basic programs and solve related to it.
DATE:
Step 2: Now we have to start the server to create the Local Hosting Environment to
make the real feel of server side operations.
Step 3: After Started the Server it looks like and you minimize it.
Take any one of the browser like Chrome, Mozilla, Internet Explorer etc.
Open the Browser here we take Chrome to check whether localhost is properly
connected or not.
Step 5: Open the Notepad for typing Program, before that you all know how to type
java programs in notepad, same like that but with some similar changes. You have to
follow the following steps.
<?php
// Display greeting message
echo "Hello, world!";
?>
Week 1 Laboratory: Understand the PHP usage and how to work with Initial
and learn to do basic programs.
DATE:
Sample Exercise: Application to Add Two Numbers using PHP and HTML
using Form Method
Input Read the Two Numbers and Post the Value From html to PHP
Output Sum of Two Numbers
Process Use Textbox to feed values and press Submit button to run.
Test Cases Input Expected Output Obtained Output
10,20 30 ????
Design
Place Two Input Box for getting Input A and B
Enter two Value and get the Result
Source Code
<html>
<head>
<title>Addition Program </title>
</head>
<body>
<form method="post">
Enter the First Number:<br>
<input type="text" name="a"> <br>
Enter the Second Number:<br>
<input type="text" name="b"> <br>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if($_POST){
//Assign A and B Value
$a = $_POST['a'];
$b = $_POST['b'];
//Calculate the Addition
$c=$a+$b;
//Print the Result
echo "The Addition of $a and $b is :".$c;
}
?>
</body>
</html>
Extra Credit
Modify the Program to Print Subtraction, Multiplication and Division of two Values.
Now you all know how to assign the Values in PHP and How to Embedded HTML
in PHP.
Exercise
In our Lab Exercise 1, need to Calculate the Factorial Number from user input.
What is Factorial?
It means multiply the value from 1 to user given input
If input is 5 means then (1 X 2 X3 X4 X 5) = so the Result will be 120.
Condition is
If the input is 0(Zero) means then Result will be 1.
Don’t Accept any Negative Values Like -1 or else.
Hint
You Must have to Know For Loop in PHP. (Example)
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
Algorithm:
Initialize variables : factorial←1,Assign value of n,
Repeat the steps until i=n factorial←factorial*i , Display factorial Result
DATE:
Like most programming languages, PHP also allows you to write code that
perform different actions based on the results of a logical or comparative test conditions
at run time. This means, you can create test conditions in the form of expressions that
evaluates to either true or false and based on these results you can perform certain
actions.
There are several control statements in PHP that you can use and make decisions:
The if statement
The if...else statement
The if...elseif....else statement
The switch...case statement
switch(n){ <?php
case label1: $num=20;
// Code to be executed switch($num){
if n=label1 case 10:
break; echo("number is equals to 10");
case label2: break;
// Code to be executed case 20:
if n=label2 echo("number is equal to 20");
break; ... break;
switch...case
default: case 30:
// Code to be executed echo("number is equal to 30");
if n is different from break;
all labels default:
} echo("number is not equal to 10,
20 or 30");
}
?>
Input Read the Number and Post the Value From html to PHP
Output To Check the Given Number is Odd or Even Using Conditional Statement
Process Use Textbox to feed values and press Submit button to run.
Test Cases Input Expected Output Obtained Output
10 Even Number ????
5 Odd Number ????
Design
Place an Input Box for getting the Input and Print the Result
Source Code
<html>
<head>
<title>Odd or Even checking using conditional Statement </title>
</head>
<body>
<form method="post">
Enter the Number:<br>
<input type="text" name="num"> <br> <br>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if($_POST){
//Getting User Value and Assign
$num = $_POST['num'];
//Check Odd or Even and Print Result
if ($num%2==0) {
echo "The Given $num is Even Number<br> ";
}
else {
echo "The Given $num is Odd Number<br> ";
}
}
?>
</body>
</html>
Extra Credit
1. Modify or Create a Program to Check Biggest of Three Numbers with If, elseif
Statement.
2. Create an Arithmetic Operations program (Example : if we give 1 Means Addition
of Two values, 2 Means Subtraction ,3 Means Multiplication and 4 Means
Division) using Switch statement. Use the Idea of Last Week Module and Solve it.
Exercise
In our Lab Exercise 2 we need to use Conditional Statement
To check the given inputted number is negative or positive.
If We Give, 10 Means Positive Number
If We Give, -10 Means Negative Number
Hint
Check the given number is Greater than Zero it must be Positive otherwise it
must be Negative
DATE:
Arrays are complex variables that allow us to store more than one value or
a group of values under a single variable name.
Input Read the Numbers and Post the Value From html to PHP
Output To Find the Minimum from Array
Process Use Text Area to feed values and press Submit button to get result.
Test Cases Input Expected Output Obtained Output
2:3:5:1:4 1(Minimum) ????
Design
Source Code
<html>
<head>
<title>Small Value in Muldimensional Array</title>
</head>
<body>
<form method="post">
Enter the numbers with Colon(:) like 2:3:5:1:4<br>
<textarea name="a"> </textarea> <br>
<input type="submit" name="submit" value="Find Minimum Value" />
</form>
</body>
</html>
<?php
if($_POST){
$a=$_POST['a'];
//to filter array values of given symbol
$new = array_values(array_filter(explode(':', $a)));
//print_r($new);
echo "The Values in the array as <br> ";
$b = 999;
//to take the value from array one by one
foreach ($new as $val) {
echo $val."<br>";
if ($val < $b) {
$b = $val;
}
}
echo "The Minimum Value is ".$b;
}
?>
Extra Credit
1. Modify or Create a program to Change instead of Colon Give like (@,#,%,&) to
Check the Program flow of above.
Exercise
In our Lab Exercise 3 we need to use Multidimensional Array to Find Maximum
Number.
Use Comma (,) to add number in Text area box like (2, 7, 6, 1, 2) among these values
find the maximum.
Hint
Same as above example, have to find maximum value in multidimensional array
DATE:
Input Read the Number and Post the Value From html to PHP
Output To check whether number is prime or not
Process Use Text Area to feed values and press Submit button to get result.
Test Cases Input Expected Output Obtained Output
2 Prime Numer ????
4 Not Prime Numer ????
Design
Place Input Box for getting Input and check the value its prime or not.
Source Code
<html>
<head>
<title>Prime number or Not</title>
</head>
<body>
<form method="post">
Enter the Number to check Prime number or Not<br>
<input type="text" name="n"> <br>
<input type="submit" name="submit" value="Check" />
</form>
</body>
</html>
<?php
if($_POST){
$n=$_POST['n'];
$check = IsPrime($n);
if ($check==0)
echo 'This is not a Prime Number.....'."\n";
else
echo 'This is a Prime Number..'."\n";
}
function IsPrime($n)
{
for($x=2; $x<$n; $x++)
{
if($n%$x ==0) { return 0;
}
}
return 1;
}
?>
Extra Credit
1. Create a program using Function to solve Sum of Natural Numbers using
Recursion.
Logic : addNumbers(n){ if(n != 0) return (n + addNumbers(n-1));else return n; }
Exercise
In our Lab Exercise 4 we need to Create user-defined function to solve GCD
(Greatest Common Divisor) Using Recursion.
Example : Given Value 1 is 36 = 2X2X3X3 and Given Value 2 is 60 = 2X2X3X5 then Multiply Common
Factor is (2X2X3=12) So GCD or HCF for 36 and 60 is 12
Hint
Algorithm: function hcf($n1, $n2)
{ if ($n2 != 0) return hcf($n2, $n1%$n2);
else return $n1; }
DATE:
Input Read two numbers, one for range and another for table value
Output To generate a table for the corresponding range
Process Use textbox and buttons to process data
Design
Source Code
<html>
<head>
<title>Generate Table</title>
</head>
<body>
<form method=‛post‛>
<h2>Addition Table</h2>
<table>
<tr>
<td>Enter the Table number </td>
<td><input type=‛text‛ name=‛tn‛></td>
</tr>
<tr>
<td>Enter the Range </td>
<td><input type=‛text‛ name=‛tr‛></td>
</tr>
<tr>
<td></td>
<td><input type=‛submit‛ name=‛submit‛ value=‛Generate Table‛ /></td>
</tr>
</table>
</form>
<?php
if($_POST){
$tn = $_POST[‘tn’];
$tr=$_POST[‘tr’];
echo ‚Addition Table for $tn as<br><br>‛;
for ($i = 1; $i <= $tr; $i++){
echo $i.‛ + ‚.$tn.‛ = ‚.($tn+$i).‛<br>‛;
}
}
?>
</body>
</html>
Extra Credit
1. Generate the Table for Subtraction and Division like same as above but you
must implement two button one for Subtraction and another for Division. If we
click Subtraction a subtraction table has to generate else if we click Division a
division table has to generate.
Exercise
In our Lab Exercise 5 we need to Generate Multiplication table for a given
number.
Hint
Use the Sample Program as model to do multiplication table.
DATE:
Sample Exercise: Application to show the Current age, month and days.
Design /Output
Source Code
<?php
$bday = new DateTime(‘11.4.1987’); // Your date of birth
$today = new Datetime(date(‘m.d.y’));
$diff = $today->diff($bday);
echo ‚Your age : $diff->y years, $diff->m month, $diff->d days<br>‛;
?>
Extra Credit
1. Using the above model program, make one text box to enter the date as
DD.MM.YYYY format and post the value to find the year, month and days using
html and php.
Exercise
In our Lab Exercise 6 we need to Compute the age of a person from his/her Date Of
Birth. To find present age have to deduce the DOB from current date and get the age.
The screen is like as
Screen1 Input
Screen2 Ouput
Hint
Use Date Time Selection HTML as
Use in PHP as
$dob=$_POST["dob"];
$dob = date("Y-m-d",strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
echo "Age is ".$diff->y;
DATE:
It allows you to work with files and directories stored on the web server.
Design
Source Code
<?php
$dir = "c:/wamp";
$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and ..
echo "<b><u>".$dir." Which has following files as ....</u> </b><br>";
foreach($files as $file){
echo $file."<br>";
}
?>
Extra Credit
1. Create a program using File, for the given folder path in text box it have to list
out the files in corresponding folder.
Exercise
In our Lab Exercise 7 Program to download a file from the server.
Hint
Step 1: Here we have know about anchor tag in html for example
<a href=‛Your File Path‛>Any Name</a>
Use this List out File in php.
Step 2: Create a folder named File, In File folder create two php files one as
index.php and another as download.php.
Index.php for list out files
Download.php for check file exist or not and download.
<?php
$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file = $path.$filename;
if(!empty($filename)){
// Check file is exists on given path.
if(file_exists($download_file))
{
header('Content-Disposition: attachment; filename=' . $filename);
readfile($download_file); exit;
} else
{
echo 'File does not exists on given path';
} }
?>
What is a Cookie?
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on
the user's computer. They are typically used to keeping track of information such as username
that the site can retrieve to personalize the page when user visit the website next time.
Parameter Description
Name The name of the cookie.
Value The value of the cookie. Do not store sensitive information since this value is
stored on the user's computer.
Expires The expiry date in UNIX timestamp format. After this time cookie will become
inaccessible. The default value is 0.
Path Specify the path on the server for which the cookie will be available. If set to /,
the cookie will be available within the entire domain.
Domain Specify the domain for which the cookie is available to e.g www.example.com.
Secure This field, if present, indicates that the cookie should be sent only if a secure
HTTPS connection exists.
Example 3
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
You can use the print_r() function like print_r($_COOKIE); to see the structure of
this $_COOKIE associative array, like you with other arrays.
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie name
and any value (such as an empty string) however this time you need the set the expiration date
in the past, as shown in the example below:
Example 4
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Exercise
In our Lab Exercise 8 Program to store the current date and time in a cookie and
display the “Last Visited” date and time on the webpage.
Hint
Script for Cookie.php
<?php
//date_default_timezone_set('Asia/Calcutta'); - You can choose any timezone
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
if(isset($_COOKIE['lastVisit']))
{
$visit = $_COOKIE['lastVisit'];
echo "<b>Your last visit was - ". $visit."</b>";
}
else
echo "Welcome to Cookie Program";
?>
Screenshot
What is a Session?
Although you can store data using cookies but it has some security issues. Since
cookies are stored on user's computer it is possible for an attacker to easily modify a
cookie content to insert potentially harmful data in your application that might break
your application.
Also every time the browser requests a URL to the server, all the cookie data for
a website is automatically sent to the server within the request. It means if you have
stored 5 cookies on user's system, each having 4KB in size, the browser needs to
upload 20KB of data each time the user views a page, which can affect your site's
performance.
You can solve both of these issues by using the PHP session. A PHP session
stores data on the server rather than user's computer. In a session based environment,
every user is identified through a unique number called session identifier or SID. This
unique session ID is used to link each user with their own information on the server like
emails, posts, etc.
Example 2
<?php
// Starting session
session_start();
// Storing session data
$_SESSION["firstname"] = "John";
$_SESSION["lastname"] = "Peter";
?>
To access the session data we set on our previous example from any other page
on the same web domain — simply recreate the session by calling session_start() and
then pass the corresponding key to the $_SESSION associative array.
Example 3
<?php
// Starting session
session_start();
// Accessing session data
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
?>
Destroying a Session
If you want to remove certain session data, simply unset the corresponding key
of the $_SESSION associative array, as shown in the following example:
Example 4
<?php
// Starting session
session_start();
// Removing session data
if(isset($_SESSION["lastname"])){
unset($_SESSION["lastname"]);
}
?>
Example 6
<?php
// Starting session
session_start();
// Destroying session
session_destroy();
?>
Sample Exercise: Work the Above Example 1, 2, 3, 4, 5, 6 and see the Output.
It will be helpful to learn how to work with session.
Exercise
In our Lab Exercise 9 Program to store the page views count in session, to increment
the count on each refresh and to show the count on webpage.
Hint
Script for Session.php
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+1;
else
$_SESSION['views']=1;
echo"views = ".$_SESSION['views'];
?>
Screenshot
Exercise
In our Lab Exercise 9 Program to draw the Face like structure using image creation.
Hint
Script for image.php
<?php
header ("Content-type:image/png");
$c=imagecreate(500,500);
$bc=imagecolorallocate($c,200,100,100);
$fc=imagecolorallocate($c,225,225,150);
$lc=imagecolorallocate($c,20,20,20);
imagefilledellipse($c,250,250,400,400,$fc);
imagefilledellipse($c,150,150,50,50,$lc);
imagefilledellipse($c,350,150,50,50,$lc);
imageline($c,250,200,280,275,$lc);
imageline($c,250,275,280,275,$lc);
imagearc($c,250,300,250,150,0,180,$lc);
imagepng($c);
imagedestroy($c);
?>
Screenshot
DATE:
Sample Exercise: Work with below example to recall the Switch statement.
switch (date('l')) {
case "Monday":
echo "Monday to take New task";
break;
case "Tuesday":
echo "Tuesday to take task2";
break;
case "Wednesday":
echo "Wednesday to take task3";
break;
case "Thursday":
echo "Thursday Review this completed task";
break;
case "Friday":
echo "Friday present the task";
break;
case "Saturday":
echo "Saturday plan to go to the movie";
break;
case "Sunday":
echo "Rest on Sunday";
break;
default:
echo "unpredicted day";
break;
}
Extra credit
1. Design the application to choose the color using switch statement to solve on
post values from html.
Sample Screen for Calculator
Exercise
In our Lab Exercise 11 Program to create a Simple Calculator.
Hint
In HTML
<select name="operator">
<option>None</option>
<option>Add</option>
<option>Subtract</option>
<option>Multiply</option>
<option>Divide</option>
<option>Square</option>
</select>
Script for Calculator.php
<?php
if (isset($_POST['submit'])) {
$result1 = $_POST['numb1'];
$result2 = $_POST['numb2'];
$operator = $_POST['operator'];
switch ($operator) {
case 'None':
echo "You need to select any operator";
break;
case 'Add':
echo "<br><b>".($result1 + $result2)."</b>";
break;
case 'Subtract':
echo "<br><b>".($result1 - $result2)."</b>";
break;
case 'Multiply':
echo "<br><b>".($result1 * $result2)."</b>";
break;
case 'Divide':
echo "<br><b>".($result1 / $result2)."</b>";
break;
case 'Square':
echo $result1*$result1."<br>" ;
echo $result2*$result2."<br>" ;
break;
}
}
?>
DATE:
What is MySQL?
MySQL is one of the most popular relational database systems being used
on the Web today. It is freely available and easy to install, however if you have installed
Wampserver it already there on your machine. MySQL database server offers several
advantages:
MySQL is easy to use, yet extremely powerful, fast, secure, and scalable.
MySQL runs on a wide range of operating systems, including UNIX or Linux,
Microsoft Windows, Apple Mac OS X, and others.
MySQL supports standard SQL (Structured Query Language).
MySQL is ideal database solution for both small and large applications.
MySQL is developed, and distributed by Oracle Corporation.
MySQL includes data security layers that protect sensitive data from intruders.
MySQL database stores data into tables like other relational database. A table is
a collection of related data, and it is divided into rows and columns.
Connecting PHP with MySQL Server
In order to store or access the data inside a MySQL database, you first need to
connect to the MySQL database server. PHP offers two different ways to connect to
MySQL server: MySQLi (Improved MySQL) and PDO (PHP Data Objects)
extensions.
While the PDO extension is more portable and supports more than twelve
different databases, MySQLi extension as the name suggests supports MySQL
database only. MySQLi extension however provides an easier way to connect to, and
execute queries on, a MySQL database server. Both PDO and MySQLi offer an
object-oriented API, but MySQLi also offers a procedural API which is relatively
easy for beginners to understand.
The hostname parameter in the above syntax specify the host name (e.g. localhost),or
IP address of the MySQL server, whereas the username and password parameters
specifies the credentials to access MySQL server, and the database parameter, if
provided will specify the default MySQL database to be used when performing queries.
Example for Connecting Database
Procedural
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
Object Oriented
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// Print host information
echo "Connect Successfully. Host info: " . $mysqli->host_info;
?>
PDO
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Print host information
echo "Connect Successfully. Host info: " .
$pdo->getAttribute(constant("PDO::ATTR_CONNECTION_STATUS"));
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
} ?>
Creating a Database
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Creating a Table
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create table query execution
$sql = "CREATE TABLE persons(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($link, $sql)){
echo "Table created successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Inserting Values in a Table
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Peter', 'Parker',
'peterparker@mail.com')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Inserting Multiple Values in a Table
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('John', 'Rambo', 'johnrambo@mail.com'),
('Clark', 'Kent', 'clarkkent@mail.com'),
('John', 'Carter', 'johncarter@mail.com'),
('Harry', 'Potter', 'harrypotter@mail.com')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Design
Steps to Follow
Go to Browser and type http://localhost/phpmyadmin
Choose Database and create new database as login
Create table name as users to follow query as
Code
<?php
$message="";
if(count($_POST)>0) {
$conn = mysqli_connect("localhost","root","","login");
$result = mysqli_query($conn,"SELECT * FROM users WHERE userName='" . $_POST["userName"] .
"' and password = '". $_POST["password"]."'");
$count = mysqli_num_rows($result);
if($count==0) {
$message = "Invalid Username or Password!";
} else {
$message = "You are successfully authenticated!";
}
}
?>
<html>
<head>
<title>User Login</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form name="frmUser" method="post" action="">
<div class="message"><?php if($message!="") { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="1" width="500"
align="center" class="tblLogin">
<tr class="tableheader">
<td align="center" colspan="2">Enter Login Details</td>
</tr>
<tr class="tablerow">
<td>
<input type="text" name="userName" placeholder="User Name"
class="login-input"></td>
</tr>
<tr class="tablerow">
<td>
<input type="password" name="password" placeholder="Password"
class="login-input"></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit"
value="Submit" class="btnSubmit"></td>
</tr> </table> </form> </body></html>
Extra Credit
1. Do validation for the above Login page like required field validation, the
password field should accept the combination of alphanumeric and special
characters.
Exercise
In our Lab Exercise 12 Program to design authentication webpage in php with MySQL
to check username and password.
Rules
Use Session to implement login and logout.
It will have Signup for new user for registration.
Doesn’t show password in the table, to do this learn hash concept.
Design Model for Signup and Login Page
Signup/Register
Login
Hint
CREATE TABLE users ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50)
NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, created_at DATETIME DEFAULT
CURRENT_TIMESTAMP );