PDO - PHP Database Extension
PDO - PHP Database Extension
https://phpgurukul.com
Index
In this PDO tutorial you will find recipes for 4 basic functions that we perform with the
database: insertion, selection, update, and deletion. The recipes are intended to work with
MySQL, but we can easily switch it with another database.
In order to connect to the database, we’ll need the database name, username, and password.
1. // DB credentials.
2. define('DB_HOST','localhost');
3. define('DB_USER','your user name');
4. define('DB_PASS','your user password');
5. define('DB_NAME','your database name');
6. // Establish database connection.
7. try
8. {
9. $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,ar
ray(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
10. }
11. catch (PDOException $e)
12. {
13. exit("Error: " . $e->getMessage());
14. }
1. $dbh = null;
Chapter 2
How to use PDO to insert data into the database?
1. CREATE TABLE IF NOT EXISTS users (id int(11) NOT NULL AUTO_INCREMENT,
2. name varchar(60) DEFAULT NULL,
3. phone varchar(12) DEFAULT NULL,
4. city varchar(60) DEFAULT NULL,
5. date_added date DEFAULT NULL,
6. PRIMARY KEY (id)
7. )
1.Write a regular SQL query but, instead of values, put named placeholders. For example:
1. $query->bindParam(':name',$name);
You can add a third parameter which filters the data before it reaches the database:
1. $query->bindParam(':name',$name,PDO::PARAM_STR);
2. $query->bindParam(':phone',$phone,PDO::PARAM_INT);
3. $query->bindParam(':city',$city,PDO::PARAM_STR);
4. $query->bindParam(':date',$date,PDO::PARAM_STR);
1. $lastInsertId = $dbh->lastInsertId();
2. if($lastInsertId>0)
3. {
4. echo "Data inserted";
5. }
6. else
7. {
8. echo "Data not inserted";
9. }
1. Write the regular select statement and again, instead of values, put named placeholders.
For example:
4. Assign the data which you pulled from the database (in the preceding step) to a variable.
Here I used the parameter PDO::FETCH_OBJ that returns the fetched data as an object. If
you’d like to fetch the data in the form of an array, use: PDO::FETCH_ASSOC.
5. Make sure that you were able to retrieve the data from the database, by counting the
number of records.
6. In case that the query returned at least one record, we can echo the records within a foreach
loop:
1. $query = $dbh->prepare($sql);
1. $tel = '06901234567';
2. $city = 'New Delhi';
3. $id = 1;
6. Check that the query has been performed and that the database has been successfully
updated.
1. $id = 1;
6. Check that the query has been performed and that the records have been successfully
CRUD Stands for create, read, update and delete record in the database.
1. <?php
2. // DB credentials.
3. define('DB_HOST','localhost');
4. define('DB_USER','root');
5. define('DB_PASS','');
6. define('DB_NAME','phpcrudpdo');
7. // Establish database connection.
8. try
9. {
10. $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS);
11. }
12. catch (PDOException $e)
13. {
14. exit("Error: " . $e->getMessage());
15. }
16. ?>
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>PHP CURD Operation using PDO Extension </title>
6. <meta name="viewport" content="width=device-width, initial-
scale=1">
7. <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.m
in.css" rel="stylesheet">
8. <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
9. <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstra
p.min.js"></script>
10. </head>
11. <body>
12.
13. <div class="container">
14.
15. <div class="row">
16. <div class="col-md-12">
17. <h3>Insert Record | PHP CRUD Operations using PDO Extension</h3>
18. <hr />
19. </div>
20. </div>
21.
22.
23. <form name="insertrecord" method="post">
24. <div class="row">
25. <div class="col-md-4"><b>First Name</b>
26. <input type="text" name="firstname" class="form-control" required>
27. </div>
28. <div class="col-md-4"><b>Last Name</b>
29. <input type="text" name="lastname" class="form-control" required>
30. </div>
31. </div>
32.
33. <div class="row">
34. <div class="col-md-4"><b>Email id</b>
35. <input type="email" name="emailid" class="form-control" required>
36. </div>
37. <div class="col-md-4"><b>Contactno</b>
38. <input type="text" name="contactno" class="form-
control" maxlength="10" required>
39. </div>
40. </div>
41.
42. <div class="row">
43. <div class="col-md-8"><b>Address</b>
44. <textarea class="form-control" name="address" required>
45. </div>
46. </div>
47. <div class="row" style="margin-top:1%">
48. <div class="col-md-8">
49. <input type="submit" name="insert" value="Submit">
50. </div>
51. </div>
52. </form>
53. </div>
54. </div>
55. </body>
56. </html>
Code for insert a record in database. Once the user filled all the data and click on the submit
button then data will be saved in the database using the below code:
1. <?php
2. // include database connection file
3. require_once'dbconfig.php';
4. if(isset($_POST['insert']))
5. {
6. // Posted Values
7. $fname=$_POST['firstname'];
8. $lname=$_POST['lastname'];
9. $emailid=$_POST['emailid'];
10. $contactno=$_POST['contactno'];
11. $address=$_POST['address'];
12. // Query for Insertion
13. $sql="INSERT INTO tblusers(FirstName,LastName,EmailId,ContactNumber,Address
) VALUES(:fn,:ln,:eml,:cno,:adrss)";
14. //Prepare Query for Execution
15. $query = $dbh->prepare($sql);
16. // Bind the parameters
17. $query->bindParam(':fn',$fname,PDO::PARAM_STR);
18. $query->bindParam(':ln',$lname,PDO::PARAM_STR);
19. $query->bindParam(':eml',$emailid,PDO::PARAM_STR);
20. $query->bindParam(':cno',$contactno,PDO::PARAM_STR);
21. $query->bindParam(':adrss',$address,PDO::PARAM_STR);
22. // Query Execution
23. $query->execute();
24. // Check that the insertion really worked. If the last inserted id is great
er than zero, the insertion worked.
25. $lastInsertId = $dbh->lastInsertId();
26. if($lastInsertId)
27. {
28. // Message for successfull insertion
29. echo "<script>alert('Record inserted successfully');</script>";
30. echo "<script>window.location.href='index.php'</script>";
31. }
32. else
33. {
34. // Message for unsuccessfull insertion
35. echo "<script>alert('Something went wrong. Please try again');</script>";
36. echo "<script>window.location.href='index.php'</script>";
37. }
38. }
39. ?>
1. <?php
2. // include database connection file
3. require_once'dbconfig.php'; ?>
4. <!DOCTYPE html>
5. <html lang="en">
6. <head>
7. <meta charset="utf-8">
8. <title>PHP CRUD Operations using PDO Extension </title>
9. <meta name="viewport" content="width=device-width, initial-scale=1">
10. <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.m
in.css" rel="stylesheet">
11. <style type="text/css">
12. </style>
13. <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
14. <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstra
p.min.js"></script>
15. </head>
16. <body>
17. <div class="container">
18. <div class="row">
19. <div class="col-md-12">
20. <h3>PHP CRUD Operations using PDO Extension</h3> <hr />
21. <a href="insert.php"><button class="btn btn-
primary"> Insert Record</button></a>
22. <div class="table-responsive">
23. <table id="mytable" class="table table-bordred table-striped">
24. <thead>
25. <th>#</th>
26. <th>First Name</th>
27. <th>Last Name</th>
28. <th>Email</th>
29. <th>Contact</th>
30. <th>Address</th>
31. <th>Posting Date</th>
32. <th>Edit</th>
33. <th>Delete</th>
34. </thead>
35. <tbody>
36.
37. <?php
38. $sql = "SELECT FirstName,LastName,EmailId,ContactNumber,Address,PostingDate
,id from tblusers";
39. //Prepare the query:
40. $query = $dbh->prepare($sql);
41. //Execute the query:
42. $query->execute();
43. //Assign the data which you pulled from the database (in the preceding step
) to a variable.
44. $results=$query->fetchAll(PDO::FETCH_OBJ);
45. // For serial number initialization
46. $cnt=1;
47. if($query->rowCount() > 0)
48. {
49. //In case that the query returned at least one record, we can echo the reco
rds within a foreach loop:
50. foreach($results as $result)
51. {
52. ?>
53. <!-- Display Records -->
54. <tr>
55. <td><?php echo htmlentities($cnt);?></td>
56. <td><?php echo htmlentities($result->FirstName);?></td>
57. <td><?php echo htmlentities($result->LastName);?></td>
58. <td><?php echo htmlentities($result->EmailId);?></td>
59. <td><?php echo htmlentities($result->ContactNumber);?></td>
60. <td><?php echo htmlentities($result->Address);?></td>
61. <td><?php echo htmlentities($result->PostingDate);?></td>
62.
63. <td><a href="update.php?id=<?php echo htmlentities($result-
>id);?>"><button class="btn btn-primary btn-
xs"><span class="glyphicon glyphicon-pencil"></span></button></a></td>
64.
65. <td><a href="index.php?del=<?php echo htmlentities($result-
>id);?>"><button class="btn btn-danger btn-
xs" onClick="return confirm('Do you really want to delete');"><span class="
glyphicon glyphicon-trash"></span></button></a></td>
66. </tr>
67.
68. <?php
69. // for serial number increment
70. $cnt++;
71. }} ?>
72. </tbody>
73. </table>
74. </div>
75. </div>
76. </div>
77. </div>
78. </body>
79. </html>
Step 5 : Update record in the database
Create update.php file. For updating a record we have to get the row id of that record and
store in $id. We access the $_GET[‘id’] variable to do it.
Code for get a record based on the given id. Through this way we can get data autofill-data in
HTML Form.
1. <?php
2. // Get the userid
3. $userid=intval($_GET['id']);
4. $sql = "SELECT FirstName,LastName,EmailId,ContactNumber,Address,PostingDate
,id from tblusers where id=:uid";
5. //Prepare the query:
6. $query = $dbh->prepare($sql);
7. //Bind the parameters
8. $query->bindParam(':uid',$userid,PDO::PARAM_STR);
9. //Execute the query:
10. $query->execute();
11. //Assign the data which you pulled from the database (in the preceding step
) to a variable.
12. $results=$query->fetchAll(PDO::FETCH_OBJ);
13. // For serial number initialization
14. $cnt=1;
15. if($query->rowCount() > 0)
16. {
17. //In case that the query returned at least one record, we can echo the reco
rds within a foreach loop:
18. foreach($results as $result)
19. {
20. ?>
21. <form name="insertrecord" method="post">
22. <div class="row">
23. <div class="col-md-4"><b>First Name</b>
24. <input type="text" name="firstname" value="<?php echo htmlentities($result-
>FirstName);?>" class="form-control" required>
25. </div>
26. <div class="col-md-4"><b>Last Name</b>
27. <input type="text" name="lastname" value="<?php echo htmlentities($result-
>LastName);?>" class="form-control" required>
28. </div>
29. </div>
30. <div class="row">
31. <div class="col-md-4"><b>Email id</b>
32. <input type="email" name="emailid" value="<?php echo htmlentities($result-
>EmailId);?>" class="form-control" required>
33. </div>
34. <div class="col-md-4"><b>Contactno</b>
35. <input type="text" name="contactno" value="<?php echo htmlentities($result-
>ContactNumber);?>" class="form-control" maxlength="10" required>
36. </div>
37. </div>
38. <div class="row">
39. <div class="col-md-8"><b>Address</b>
40. <textarea class="form-
control" name="address" required><?php echo htmlentities($result-
>Address);?>
41. </div>
42. </div>
43. <?php }} ?>
44.
45. <div class="row" style="margin-top:1%">
46. <div class="col-md-8">
47. <input type="submit" name="update" value="Update">
48. </div>
49. </div>
1. <?php
2. // include database connection file
3. require_once'dbconfig.php';
4. if(isset($_POST['update']))
5. {
6. // Get the userid
7. $userid=intval($_GET['id']);
8. // Posted Values
9. $fname=$_POST['firstname'];
10. $lname=$_POST['lastname'];
11. $emailid=$_POST['emailid'];
12. $contactno=$_POST['contactno'];
13. $address=$_POST['address'];
14. // Query for Updation
15. $sql="update tblusers set FirstName=:fn,LastName=:ln,EmailId=:eml,ContactNu
mber=:cno,Address=:adrss where id=:uid";
16. //Prepare Query for Execution
17. $query = $dbh->prepare($sql);
18. // Bind the parameters
19. $query->bindParam(':fn',$fname,PDO::PARAM_STR);
20. $query->bindParam(':ln',$lname,PDO::PARAM_STR);
21. $query->bindParam(':eml',$emailid,PDO::PARAM_STR);
22. $query->bindParam(':cno',$contactno,PDO::PARAM_STR);
23. $query->bindParam(':adrss',$address,PDO::PARAM_STR);
24. $query->bindParam(':uid',$userid,PDO::PARAM_STR);
25. // Query Execution
26. $query->execute();
27. // Mesage after updation
28. echo "<script>alert('Record Updated successfully');</script>";
29. // Code for redirection
30. echo "<script>window.location.href='index.php'</script>";
31. }
32. ?>
Step 6 : Delete a record from the database
Place this code in the index.php file.
1. <?php
2. // include database connection file
3. require_once'dbconfig.php';
4. // Code for record deletion
5. if(isset($_REQUEST['del']))
6. {
7. //Get row id
8. $uid=intval($_GET['del']);
9. //Qyery for deletion
10. $sql = "delete from tblusers WHERE id=:id";
11. // Prepare query for execution
12. $query = $dbh->prepare($sql);
13. // bind the parameters
14. $query-> bindParam(':id',$uid, PDO::PARAM_STR);
15. // Query Execution
16. $query -> execute();
17. // Mesage after updation
18. echo "<script>alert('Record Updated successfully');</script>";
19. // Code for redirection
20. echo "<script>window.location.href='index.php'</script>";
21. }
22.
23. ?>
Chapter 7
1. <?php
2. // DB credentials.
3. define('DB_HOST','localhost'); // Host name
4. define('DB_USER','root'); // db user name
5. define('DB_PASS',''); // db user password name
6. define('DB_NAME','pdosignup'); // db name
7. // Establish database connection.
8. try
9. {
10. $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS);
11. }
12. catch (PDOException $e)
13. {
14. exit("Error: " . $e->getMessage());
15. }
16. ?>
Step3.1 HTML form with html5 validation pattern. In this form every input filed valid with
HTML5 pattern validation
Fullname can contain any letters only with spaces
pattern=”[a-zA-Z\s]+”
pattern=”^[a-zA-Z][a-zA-Z0-9-_.]{5,12}$”
type=“email”
Mobile Number Contain only 10 digit numeric values
pattern=”[0-9]{10}” maxlength=”10″
pattern=”^\S{4,}$” onchange=”this.setCustomValidity(this.validity.patternMismatch ?
‘Please enter the same Password as above’ : ”)”
Step3.2 Check the username and email availability in the data using j-query
j-query code
1. <?php
2. require_once("config.php");
3. // Code for checking username availabilty
4. if(!emptyempty($_POST["username"])) {
5. $uname= $_POST["username"];
6. $sql ="SELECT UserName FROM userdata WHERE UserName=:uname";
7. $query= $dbh -> prepare($sql);
8. $query-> bindParam(':uname', $uname, PDO::PARAM_STR);
9. $query-> execute();
10. $results = $query -> fetchAll(PDO::FETCH_OBJ);
11. if($query -> rowCount() > 0)
12. {
13. echo "<span style='color:red'> Username already exists.</span>";
14. } else{
15. echo "<span style='color:green'> Username available for Registration.</span
>";
16. }
17. }
18.
19. // Code for checking email availabilty
20. if(!emptyempty($_POST["email"])) {
21. $email= $_POST["email"];
22. $sql ="SELECT UserEmail FROM userdata WHERE UserEmail=:email";
23. $query= $dbh -> prepare($sql);
24. $query-> bindParam(':email', $email, PDO::PARAM_STR);
25. $query-> execute();
26. $results = $query -> fetchAll(PDO::FETCH_OBJ);
27. if($query -> rowCount() > 0)
28. {
29. echo "<span style='color:red'>Email-id already exists.</span>";
30. } else{
31. echo "<span style='color:green'>Email-
id available for Registration.</span>";
32. }
33. }
34.
35. ?>
1. <?php
2. //Database Configuration File
3. include('config.php');
4. error_reporting(0);
5. if(isset($_POST['signup']))
6. {
7. //Getting Post Values
8. $fullname=$_POST['fname'];
9. $username=$_POST['username'];
10. $email=$_POST['email'];
11. $mobile=$_POST['mobilenumber'];
12. $password=md5($_POST['password']);
13. // Query for validation of username and email-id
14. $ret="SELECT * FROM userdata where (UserName=:uname || UserEmail=:uemail)"
;
15. $queryt = $dbh -> prepare($ret);
16. $queryt->bindParam(':uemail',$email,PDO::PARAM_STR);
17. $queryt->bindParam(':uname',$username,PDO::PARAM_STR);
18. $queryt -> execute();
19. $results = $queryt -> fetchAll(PDO::FETCH_OBJ);
20. if($queryt -> rowCount() == 0)
21. {
22. // Query for Insertion
23. $sql="INSERT INTO userdata(FullName,UserName,UserEmail,UserMobileNumber,Log
inPassword) VALUES(:fname,:uname,:uemail,:umobile,:upassword)";
24. $query = $dbh->prepare($sql);
25. // Binding Post Values
26. $query->bindParam(':fname',$fullname,PDO::PARAM_STR);
27. $query->bindParam(':uname',$username,PDO::PARAM_STR);
28. $query->bindParam(':uemail',$email,PDO::PARAM_STR);
29. $query->bindParam(':umobile',$mobile,PDO::PARAM_INT);
30. $query->bindParam(':upassword',$password,PDO::PARAM_STR);
31. $query->execute();
32. $lastInsertId = $dbh->lastInsertId();
33. if($lastInsertId)
34. {
35. $msg="You have signup Scuccessfully";
36. }
37. else
38. {
39. $error="Something went wrong.Please try again";
40. }
41. }
42. else
43. {
44. $error="Username or Email-id already exist. Please try again";
45. }
46. }
47. ?>
Here is the full code that we have written for signup(signup.php) :
1. <?php
2. //Database Configuration File
3. include('config.php');
4. error_reporting(0);
5. if(isset($_POST['signup']))
6. {
7. //Getting Post Values
8. $fullname=$_POST['fname'];
9. $username=$_POST['username'];
10. $email=$_POST['email'];
11. $mobile=$_POST['mobilenumber'];
12. $password=md5($_POST['password']);
13. // Query for validation of username and email-id
14. $ret="SELECT * FROM userdata where (UserName=:uname || UserEmail=:uemail)"
;
15. $queryt = $dbh -> prepare($ret);
16. $queryt->bindParam(':uemail',$email,PDO::PARAM_STR);
17. $queryt->bindParam(':uname',$username,PDO::PARAM_STR);
18. $queryt -> execute();
19. $results = $queryt -> fetchAll(PDO::FETCH_OBJ);
20. if($queryt -> rowCount() == 0)
21. {
22. // Query for Insertion
23. $sql="INSERT INTO userdata(FullName,UserName,UserEmail,UserMobileNumber,Log
inPassword) VALUES(:fname,:uname,:uemail,:umobile,:upassword)";
24. $query = $dbh->prepare($sql);
25. // Binding Post Values
26. $query->bindParam(':fname',$fullname,PDO::PARAM_STR);
27. $query->bindParam(':uname',$username,PDO::PARAM_STR);
28. $query->bindParam(':uemail',$email,PDO::PARAM_STR);
29. $query->bindParam(':umobile',$mobile,PDO::PARAM_INT);
30. $query->bindParam(':upassword',$password,PDO::PARAM_STR);
31. $query->execute();
32. $lastInsertId = $dbh->lastInsertId();
33. if($lastInsertId)
34. {
35. $msg="You have signup Scuccessfully";
36. }
37. else
38. {
39. $error="Something went wrong.Please try again";
40. }
41. }
42. else
43. {
44. $error="Username or Email-id already exist. Please try again";
45. }
46. }
47. ?>
48.
49. <!DOCTYPE html>
50. <html lang="en">
51. <head>
52. <meta charset="utf-8">
53. <title>PDO | Registration Form</title>
54. <meta name="viewport" content="width=device-width, initial-
scale=1">
55. <link href="https://netdna.bootstrapcdn.com/twitter-
bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
56. <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
57. <script src="https://netdna.bootstrapcdn.com/twitter-
bootstrap/2.3.2/js/bootstrap.min.js"></script>
58. <style>
59. .errorWrap {
60. padding: 10px;
61. margin: 0 0 20px 0;
62. background: #fff;
63. border-left: 4px solid #dd3d36;
64. -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
65. box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
66. }
67. .succWrap{
68. padding: 10px;
69. margin: 0 0 20px 0;
70. background: #fff;
71. border-left: 4px solid #5cb85c;
72. -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
73. box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
74. }
75. </style>
76. <!--Javascript for check username availability-->
77. <script>
78. function checkUsernameAvailability() {
79. $("#loaderIcon").show();
80. jQuery.ajax({
81. url: "check_availability.php",
82. data:'username='+$("#username").val(),
83. type: "POST",
84. success:function(data){
85. $("#username-availability-status").html(data);
86. $("#loaderIcon").hide();
87. },
88. error:function (){
89. }
90. });
91. }
92. </script>
93.
94. <!--Javascript for check email availability-->
95. <script>
96. function checkEmailAvailability() {
97. $("#loaderIcon").show();
98. jQuery.ajax({
99. url: "check_availability.php",
100. data:'email='+$("#email").val(),
101. type: "POST",
102. success:function(data){
103.
104. $("#email-availability-status").html(data);
105. $("#loaderIcon").hide();
106. },
107. error:function (){
108. event.preventDefault();
109. }
110. });
111. }
112. </script>
113.
114.
115. </head>
116. <body>
117. <form class="form-horizontal" action='' method="post">
118. <fieldset>
119. <div id="legend" style="padding-left:4%">
120. <legend class="">Register | <a href="index.php">Sign in</a></l
egend>
121. </div>
122. <!--Error Message-->
123. <?php if($error){ ?><div class="errorWrap">
124. <strong>Error </strong> : <?php echo htmlentities($e
rror);?></div>
125. <?php } ?>
126. <!--Success Message-->
127. <?php if($msg){ ?><div class="succWrap">
128. <strong>Well Done </strong> : <?php echo htmlentitie
s($msg);?></div>
129. <?php } ?>
130.
131. <div class="control-group">
132. <!-- Full name -->
133. <label class="control-
label" for="fullname">Full Name</label>
134. <div class="controls">
135. <input type="text" id="fname" name="fname" pattern="[a-zA-
Z\s]+" title="Full name must contain letters only" class="input-
xlarge" required>
136. <p class="help-
block">Full can contain any letters only</p>
137. </div>
138. </div>
139. <div class="control-group">
140. <!-- Username -->
141. <label class="control-
label" for="username">Username</label>
142. <div class="controls">
143. <input type="text" id="username" name="username" onBlur="che
ckUsernameAvailability()" pattern="^[a-zA-Z][a-zA-Z0-9-
_.]{5,12}$" title="User must be alphanumeric without spaces 6 to 12 chars"
class="input-xlarge" required>
144. <span id="username-availability-status" style="font-
size:12px;"></span>
145. <p class="help-
block">Username can contain any letters or numbers, without spaces 6 to 12
chars </p>
146. </div>
147. </div>
148.
149. <div class="control-group">
150. <!-- E-mail -->
151. <label class="control-label" for="email">E-mail</label>
152. <div class="controls">
153. <input type="email" id="email" name="email" placeholder="" o
nBlur="checkEmailAvailability()" class="input-xlarge" required>
154. <span id="email-availability-status" style="font-
size:12px;"></span>
155. <p class="help-block">Please provide your E-mail</p>
156. </div>
157. </div>
158.
159. <div class="control-group">
160. <!-- Mobile Number -->
161. <label class="control-
label" for="mobilenumber">Mobile Number </label>
162. <div class="controls">
163. <input type="text" id="mobilenumber" name="mobilenumber" pat
tern="[0-
9]{10}" maxlength="10" title="10 numeric digits only" class="input-
xlarge" required>
164. <p class="help-
block">Mobile Number Contain only 10 digit numeric values</p>
165. </div>
166. </div>
167. <div class="control-group">
168. <!-- Password-->
169. <label class="control-label" for="password">Password</label>
170. <div class="controls">
171. <input type="password" id="password" name="password" pattern
="^\S{4,}$" onchange="this.setCustomValidity(this.validity.patternMismatch
? 'Must have at least 4 characters' : ''); if(this.checkValidity()) form.pa
ssword_two.pattern = this.value;" required class="input-xlarge">
172. <p class="help-
block">Password should be at least 4 characters</p>
173. </div>
174. </div>
175.
176. <div class="control-group">
177. <!-- Confirm Password -->
178. <label class="control-
label" for="password_confirm">Password (Confirm)</label>
179. <div class="controls">
180. <input type="password" id="password_confirm" name="password_
confirm" pattern="^\S{4,}$" onchange="this.setCustomValidity(this.validity.
patternMismatch ? 'Please enter the same Password as above' : '')"" class=
"input-xlarge">
181. <p class="help-block">Please confirm password</p>
182. </div>
183. </div>
184.
185. <div class="control-group">
186. <!-- Button -->
187. <div class="controls">
188. <button class="btn btn-
success" type="submit" name="signup">Signup </button>
189. </div>
190. </div>
191. </fieldset>
192. </form>
193. <script type="text/javascript">
194.
195. </script>
196. </body>
197. </html>
1. <?php
2. session_start();
3. //Database Configuration File
4. include('config.php');
5. error_reporting(0);
6. if(isset($_POST['login']))
7. {
8. // Getting username/ email and password
9. $uname=$_POST['username'];
10. $password=md5($_POST['password']);
11. // Fetch data from database on the basis of username/email and password
12. $sql ="SELECT UserName,UserEmail,LoginPassword FROM userdata WHERE (Use
rName=:usname || UserEmail=:usname) and (LoginPassword=:usrpassword)";
13. $query= $dbh -> prepare($sql);
14. $query-> bindParam(':usname', $uname, PDO::PARAM_STR);
15. $query-> bindParam(':usrpassword', $password, PDO::PARAM_STR);
16. $query-> execute();
17. $results=$query->fetchAll(PDO::FETCH_OBJ);
18. if($query->rowCount() > 0)
19. {
20. $_SESSION['userlogin']=$_POST['username'];
21. echo "<script type='text/javascript'> document.location = 'welcome.php'
; </script>";
22. } else{
23. echo "<script>alert('Invalid Details');</script>";
24. }
25. }
26. ?>
1. <?php
2. session_start();
3. include('config.php');
4. // Validating Session
5. if(strlen($_SESSION['userlogin'])==0)
6. {
7. header('location:index.php');
8. }
9. else{
10. ?>
11.
12. <!DOCTYPE html>
13. <html lang="en">
14. <head>
15. <meta charset="utf-8">
16. <title>PDO | Welcome Page</title>
17. <meta name="viewport" content="width=device-width, initial-
scale=1">
18. <link href="https://netdna.bootstrapcdn.com/twitter-
bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
19. <style type="text/css">
20. .center {text-align: center; margin-left: auto; margin-
right: auto; margin-bottom: auto; margin-top: auto;}
21.
22. </style>
23. <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
24. <script src="https://netdna.bootstrapcdn.com/twitter-
bootstrap/2.3.2/js/bootstrap.min.js"></script>
25. </head>
26. <body>
27. <div class="container">
28. <div class="row">
29. <div class="span12">
30. <div class="hero-unit center">
31. <?php
32. // Code for fecthing user full name on the bassis of username or email.
33. $username=$_SESSION['userlogin'];
34. $query=$dbh-
>prepare("SELECT FullName FROM userdata WHERE (UserName=:username || UserE
mail=:username)");
35. $query->execute(array(':username'=> $username));
36. while($row=$query->fetch(PDO::FETCH_ASSOC)){
37. $username=$row['FullName'];
38. }
39. ?>
40.
41. <h1>Welcome Back <font face="Tahoma" color="red"><?php echo $user
name;?> ! </font></h1>
42. <br />
43. <p>Lorem ipsum dolor sit amet, sit veniam senserit mediocritatem
et, melius aperiam complectitur an qui. Ut numquam vocibus accumsan mel. Pe
r ei etiam vituperatoribus, ne quot mandamus conceptam has, pri molestiae c
onstituam quaerendum an. In molestiae torquatos eam.
44. </p>
45. <a href="logout.php" class="btn btn-large btn-
info"><i class="icon-home icon-white"></i> Log me out</a>
46. </div>
47. <br />
48.
49. </div>
50. <br />
51. <!-- By ConnerT HTML & CSS Enthusiast -->
52. </div>
53. </div>
54. </div>
55.
56. </body>
57. </html>
58. <?php } ?>
1. <?php
2. session_start();
3. unset($_SESSION['userlogin']); // unset session variable
4. session_destroy(); // destroy session
5. header("location:index.php");
6. ?>