Sei sulla pagina 1di 33

jQuery AJAX example with php MySQL –

download source code


jQuery AJAX example with php MySQL
jQuery and Ajax are buzzwords now a days in web development community and it is
a must have skill for a web developer. In this tutorial we are going to explore jQuery
AJAX example with php MySQL and how we can send an AJAX get request using
jQuery to fetch data from MySQL database server. Let us explore what is Ajax and
why it is so popular with jQuery and see how we can perform an AJAX GET request
to get data from server.

Why is AJAX and jQuery are important?

AJAX stands for Asynchronous JavaScript and XML. It


uses XMLHttpRequest object to communicate with Server. It can send to server and
receive data from server in different formats like JSON, XML, HTML or Text
asynchronously, that prevents whole page from refreshing.

jQuery is a light weight JavaScript library and has wide range of plugins available for
doing different tasks very easily. jQuery hides complexities of plain JavaScript and
provides a quick way to perform different tasks. It has several methods that are used
to perform AJAX requests.

jQuery AJAX Methods

$.ajax – This method performs an asynchronous request.

$.get – This method performs HTTP AJAX GET request.

$.getJSON – This method get JSON encoded data using AJAX HTTP GET request

$.post – This method load data from server using AJAX HTTP POST request.

Perform a AJAX GET request to get data from server

Using jQuery, AJAX GET request can fetch data from server. The task we are going
to do is fetch users from MySQL database using jQuery AJAX.
1. Create a MySQL table and insert data

2. Create HTML form and jQuery script to perform AJAX GET Request to PHP
MySQL Server

3. Write a PHP script to receive request from client and fetch data from MySQL
database and send a JSON encoded result to client

1. Create MySql database and table using PHPMyAdmin

1. Create a MySQL database : dbusers

2. Create a table in database : users

3. Insert data into the table

create DATABASE dbusers;

CREATE TABLE IF NOT EXISTS users ( id int(11) NOT NULL,

first_name varchar(255) NOT NULL,

last_name varchar(255) NOT NULL,

email varchar(255) NOT NULL )

ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE users ADD PRIMARY KEY (id);

ALTER TABLE users MODIFY id int(11) NOT NULL AUTO_INCREMENT;

INSERT INTO users (id, first_name, last_name, email)

VALUES (NULL, "John", "Doe", "john.doe@example.com"), (NULL, "Mark",


"William", "mark.william@example.com");

HTML and jQuery Code

Now I hope you have already installed PHP, Apache, MySQL on your system using
WAMP, XAMPP or MAMP.

1. Create folder for the project name ajaxjquery inside your root directory.

2. Create a file index.php inside ajaxjquery directory.


3. Add HTML code that will display a button.

4. When user will click on a button an AJAX request will be posted to PHP MySQL
server.

5. PHP MySQL will return JSON encoded result back to client end.

Create Form and button onClick event code

<html>

<head>

<title>jQuery AJAX Example</title>

</head>

<body>

<p><strong>Click on button to view users</strong></p>

<div id = "container" >

<div id="records"></div>

<p>
<input type=”button” id = "getusers" value = "Get Users" />
</p>

</div>

<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>

<script type=”text/javascript”>

$(function(){ $("#getusers").on(‘click’, function(){


$.ajax({ method: "POST", url: "getrecords.php", })

.done(function( data ) {
var result = $.parseJSON(data);

var string = '<table>


<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<tr>';

/* from result create a string of data and append to the div */

$.each( result, function( key, value ) {


string += <tr>
<td>”+value['id'] + "</td>
<td> " + value[‘first_name’]+'
'+value['last_name']+'</td>
<td> '+ value[’email’]+”</td> </tr>”; });
string += '</table>';

$("#records").html(string);
});
});
});

</script>

</body>

</html>

In HTML code we create a button. Button’s onclick method will perform a GET
request and will embed the result to a div.

jQuery $function()

Inside first script tag we called jQuery from jQuery CDN so we can perform an AJAX
request. In second script tag we have a code block inside
$(function(){

The code above is a jQuery code snippet that make sure the code inside this block
executes after whole page is loaded. The next code snippet

jQuery Ajax Code

$("#getusers").on('click', function(){

$.ajax({
method: "GET", url: "getrecords.php",

}).done(function( data ) {

var result = $.parseJSON(data);

var string = '<table><tr><th>#</th><th>Name</th><th>Email</th></tr>';

//from result create a string of data and append to the div


$.each( result, function( key, value ) {

string += "<tr>
<td>"+value['id'] + "</td>
<td> " + value['first_name']+' '+value['last_name']+'</td>
<td> '+ value['email']+"</td>
</tr>";

});

string += '</table>';

$("#records").html(string);
});

In the script above when a user clicks on the button whose id is #getusers . An AJAX
request is posted to a PHP page named getrecords.php. PHP page returns a JSON
Encoded result. Using jQuery’s method $.parseJSON result is decoded and a loop is
performed through data array. Inside loop user information is concatenated inside a
table and then all the records are appended to a div using HTMLmethod in jQuery.

PHP code to access records from database

In this last step we have to create a PHP script that will accept a request and send back
JSON encoded result. So following are steps.

1. Connect to MySQL database.

2. Perform a query after successful connection to database.

3. After query execution encode the results in a JSON array and return back to client.

Database connection

To connect to MySQL database server we have to provide hostname, username,


password and database name to mysqli function. $_POST super global array contains
data from client side. On client side if we use method post, then on server data is
inside $_POST super global array and if method in client form is GET then on server
data is inside $_GET super global array.
<?php

$host = "localhost";
$username = "root";

$password = "";

$dbname = "dbusers";
$result_array = array();

/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);

/* Check connection */
if ($conn->connect_error) {

die("Connection to database failed: " . $conn->connect_error);


}

/* SQL query to get results from database */

$sql = "SELECT id, first_name, last_name, email FROM users ";

$result = $conn->query($sql);

/* If there are results from database push to result array */

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

array_push($result_array, $row);

/* send a JSON encded array to client */


echo json_encode($result_array);

$conn->close();

?>

In this article we have explored jQuery’s AJAX GET method to fetch results from
Server.

jQuery AJAX Post method example


Now we are going to explore jQuery AJAX post method .

1. Create a file postdata.php inside ajaxjquery directory.

2. Add HTML code that will display form fields with a button.

3. When user fills in the form and clicks on button an AJAX POST request is sent to
server.

4. After validations data is saved to database.

5. Server returns JSON encoded result back to client.

HTML form and jQuery Code


<html>

<head>
<title>jQuery AJAX POST Example</title>
</head>

<body>
<p>
<strong>Please fill in the form and click save.</strong>
</p>
<div id = "container" >

<div id="message"></div>

<p>

<form name='form1'>

<label>First Name:</label>&nbsp;
<input type='text' placeholder='First Name' name='first_name' id=
'first_name' required ><br />

<label>Last Name:</label>&nbsp;

<input type='text' placeholder='Last Name' name='last_name' id='last_name'


required ><br />

<label>Email:</label>&nbsp;

<input type='email' 'name='email' placeholder='email' id='email' required


><br />

<input type="button" id = "saveusers" value = "Save" />

</form>

</p>

</div>

<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>

<script type=”text/javascript”>

$(function(){

$("#saveusers").on('click', function(){

var fname = $("#first_name").val();

var lname = $("#last_name").val();

var email = $("#email").val();

$.ajax({

method: "POST",
url: "saverecords.php",

data: {"first_name": first_name, "last_name": last_name,


"email": email},

}).done(function( data ) {
var result = $.parseJSON(data);

var str = '';

if(result == 1) {

str = 'User record saved successfully.';

}else if( result == 2) {


str == 'All fields are required.';

} else{
str = 'User data could not be saved. Please try again';
}

$("#message").css('color', 'red').html(str);

});

});

</script>
</body>

</html>

HTML form explanation

In the form tag we have created text boxes for first_name, last_name and email. New
HTML5 attributes such as placehoder (Used to show a text to user inside text filed,
This text disappears as user starts typing) and required (Used to validate so field is
not empty) are used.

In HTML5 some new elements are also introduced like email. Email type will force
user to enter a valid email address.

jQuery code explanation

Below the form code there is <script> tag to include jQuery. In next <script> there is
a function that executes on onclick event of button with id saveusers.

We are using .on function of jQuery that has two arguments.

1. event (click)
2. callback function. When user will click on button, callback function executes. In
function get values of first name, last name and email using val() function in jQuery
and save in variables.

$.AJAX function and validation

In $.ajax function we specify method to send data as POST, URL of PHP


script and data to post. In .done function we check the response sent by server. Based
on server response create a message , change color of text to red using jQuery’s .css
function and then show it to user using .html function.

PHP server side code to save data to MySQL database

We create a connection to MySQL server, get data from client side and finally after
validations, save data to database. In newer PHP versions mysql_* functions are
deprecated.

Now mysqli or PDO functions are used, these newer functions provide prepared
statements for preventing sql injection attacks.

Data validation

We have to perform server side validation as well. If any of the text box in form was
empty, we have to show user an error message by sending $result value as 2, We
create an prepared statement for insert and bind the parameters. After query
execution success result is sent back to client end.

Insert data to database using jQuery ajax post

<?php

$host = "localhost";

$username = "root";

$password = "";

$dbname = "test";

$result = 0;

/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);

/* Check connection */
if ($conn->connect_error) {
die("Connection to database failed: " . $conn->connect_error);
}

/* Get data from Client side using $_POST array */

$fname = $_POST['first_name'];

$lname = $_POST['last_name'];

$email = $_POST['email'];

/* validate whether user has entered all values. */

if(!$fname || !$lname || !$email){

$result = 2;

}elseif (!strpos($email, "@") || !strpos($email, ".")) {

$result = 3;

}else {

//SQL query to get results from database


$sql = "insert into users (first_name, last_name, email) values (?, ?,
?) ";

$stmt = $conn->prepare($sql);

$stmt->bind_param('sss', $fname, $lname, $email);

if($stmt->execute()){

$result = 1;

echo $result;

$conn->close();

Summary

To summarize in this tutorial we learned about jQuery AJAX and how to


perform GET and POST requests to server. Click here to download example source
code for jQuery AJAX GET method and Click here to download jQuery AJAX POST
method source code.

Please leave your comments and feedback below. To keep yourself updated please
subscribe to our newsletter.
Drop down - get value from database set
option to selected
<?php

(isset($_POST["company"])) ? $company = $_POST["company"] : $company=1;

?>

<form>
<select id="company" name="company">
<option <?php if ($company == 1 ) echo 'selected' ; ?>
value="1">Apple</option>
<option <?php if ($company == 2 ) echo 'selected' ; ?>
value="2">Samsung</option>
<option <?php if ($company == 3 ) echo 'selected' ; ?>
value="3">HTC</option>
</select>
</form>

I couldn't find any solution for this. I need to get the database value ("Default") as the pre-
selected value of the drop down list.

<select name="listCustomer" id="listCustomer">


<?php
$sql = mysqli_query($connection,"SELECT customer_name FROM customers");
while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)){
echo "<option value=\"" . $row['customer_name'] . "\">" . $row['customer_name'] . "</option>";}
?>
</select>

Answer:- Just create a variable before the echo, something like:

$selected = ((strtolower($row['customer_name']) == 'default') ? 'selected' : '');


then change the echo to this:

echo '<option '.$selected.' value="'.$row['customer_name'].'">'.$row['customer_name'].'</option>';

This can be accomplished using an if statement on the customer_name

$sql = mysqli_query($connection,"SELECT customer_name FROM customers");


while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)){
if($row["customer_name"] === "Default"){
echo "<option value=\"" . $row['customer_name'] . "\" selected>" . $row['customer_name'] . "</option>";
} else {
echo "<option value=\"" . $row['customer_name'] . "\">" . $row['customer_name'] . "</option>";
}
}
?>
Note the selected tag on the first echo.

$query="SELECT customer_name FROM customers";


$result = @mysql_query ($query);
echo "<select name=customer_name value=' '>";
while($drop=@mysql_fetch_array($result)){
echo "<option value=$drop[customer_name]>$drop[customer_name]</option>";
}
echo "</select>";

HI you can do this way

//db connection
mysql_connect("localhost","user","password");
mysql_select_db("database");

//query
$sql=mysql_query("SELECT id,name FROM table");
if(mysql_num_rows($sql)){
$select= '<select name="select">';
while($rs=mysql_fetch_array($sql)){
$select.='<option value="'.$rs['id'].'">'.$rs['name'].'</option>';
}
}
$select.='</select>';
echo $select;

Set the default value in dynamic dropdown using php


Code:
$cat_res = mysql_query("SELECT * FROM t_category ORDER BY cat_code
DESC");
$category_result = mysql_query("SELECT * FROM t_category ORDER BY
cat_code DESC");

<select name="drp_category" size="1" id="Select1"> <?php


while($row=mysql_fetch_array($category_result)){?>
<option value="<?php echo $row['cat_category'];?>" <?php
if($cat_res == $row['cat_category']){ ?> selected <?php }?> > <?php
echo $row['cat_category']; ?></option>
<?php } ?>
</select>

using if condition you can check the first value or currently added value selected

Change Textbox value when an item is selected


in drop down box
$('#quantity').change(function(){
var qty = $('#quantity').val();
var price = $('#productPrice').val();
var total = price * qty;
$("#totalprice").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pricesection">
<input type="hidden" id="productPrice" value="340"/>
Quantity:
<select id="quantity">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Total: $
<input type="text" id="totalprice" value="340"/>

</div>

display html form values in same page after


submit
I have a HTML form and I need to display the form field values below the form after user
clicks the submit button. How can I do this using HTML and JavaScript?

Here is one way to do it.


12down vote <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
}
</script>

</head>
<body>

<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>

<input type="submit" onclick="showInput();"><br/>


<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
And this is what it looks like when run.Cheers.

One more way to do it (if you use form), note that input type is button

<input type="button" onclick="showMessage()" value="submit" />


Complete code is:

<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
But you can do it even without form:

<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
Here you can use either submit or button:

<input type="submit" onclick="showMessage()" value="submit" />


No need to set

return false;
from JavaScript function for neither of those two examples.

This works.

<html>
<head>
<script type = "text/javascript">
function write_below(form)
{
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML="Your input was:"+input;
return false;
}
</script>
</head>

<!--Insert more code here-->


<body>
<form name='write' onsubmit='return write_below(this);'>
<input type = "text" name='input_to_write'>
<input type = "button" value = "submit" />
</form>
<div id='write_here'></div></body>
</html>
Returning false from the function never posts it to other page,but does edit the html content.

<script type = "text/javascript">


function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>

<!--Insert more code here-->

<input type = "text" id = "textfield">


<input type = "button" onclick = "get('textfield')" value = "submit">
Next time you ask a question here, include more detail and what you have tried.

<html>
<body>
<!-- Trigger/Open The Modal -->
<div style="background-color:#0F0F8C ;height:45px">
<h2 style="color: white">LOGO</h2>
</div>
<div>
<button id="myBtn">&emsp;+ Add Task &emsp;</button>
</div>
<div>
<table id="tasksTable">
<thead>
<tr style="background-color:rgba(201, 196, 196, 0.86)">
<th style="width: 150px;">Name</th>
<th style="width: 250px;">Desc</th>
<th style="width: 120px">Date</th>
<th style="width: 120px class=fa fa-trash"></th>
</tr>

</thead>
<tbody></tbody>
</table>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->


<div class="modal-content">

<div class="modal-header">
<span class="close">&times;</span>
<h3> Add Task</h3>
</div>

<div class="modal-body">
<table style="padding: 28px 50px">
<tr>
<td style="width:150px">Name:</td>
<td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>
</tr>
<tr>
<td>
Desc:
</td>
<td>
<textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>
</td>
</tr>
</table>
</div>

<div class="modal-footer">
<button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>
<br>
<br>
<br>
</div>

</div>
</div>

<script>
var tasks = [];
var descs = [];

// Get the modal


var modal = document.getElementById('myModal');

// Get the button that opens the modal


var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal


var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal


btn.onclick = function () {
modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal


span.onclick = function () {
modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it


window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var rowCount = 1;
function addTasks() {
var temp = 'style .fa fa-trash';
tasks.push(document.getElementById("taskname").value);
descs.push(document.getElementById("taskdesc").value);
var table = document.getElementById("tasksTable");
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = tasks[rowCount - 1];
cell2.innerHTML = descs[rowCount - 1];
cell3.innerHTML = getDate();
cell4.innerHTML='<td class="fa fa-trash"></td>';
rowCount++;
modal.style.display = "none";
}

function getDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!

var yyyy = today.getFullYear();

if (dd < 10) {


dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);
return today;
}
</script>
</body>

</html>

Javascript dropdownlist
Javascript Combobox
A dropdown list provides a method of selecting only one option from a lots of options while only
using up as much space as a single option except while a selection is being made.

Javascript Select options

Source Code

<html>
<body>
<select id="colors">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
</select>
</body>
</html>

Get the selected value of dropdown list using JavaScript


The following program shows how to get selected index value or selected text from a Javascript
dropdownlist
Monday

Get Selected Day

Source Code

<html>
<head>
<script type="text/javascript">
function findDay()
{
var eID = document.getElementById("daysCombo");
var dayVal = eID.options[eID.selectedIndex].value;
var daytxt = eID.options[eID.selectedIndex].text;
alert("Selected Item " + daytxt + ", Value " + dayVal);
}
</script>
</head>
<body>
<select id="daysCombo">
<option value="1">Sunday</option>
<option value="2" selected="selected">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<br><br>
<button onclick="findDay()">Get Selected Day</button>
</body>
</html>

Also the following code will help you to select item from selection option by index number.

document.getElementById("daysCombo").options.item(6).text;

dropdown list onchange event


The following program shows how to dropdown list onchange event in Javascript. While you
change the selection from javascriptcombobox you can see the color of Div element is changing.

White

Change my color

Source Code

<html>
<head>
<script type="text/javascript">
function changeColor() {
var eID = document.getElementById("colors");
var colorVal = eID.options[eID.selectedIndex].value;
var colortxt = eID.options[eID.selectedIndex].text;
document.getElementById('colorDiv').style.background=colortxt;
}
</script>
</head>
<body>
<select id="colors" onchange="changeColor()">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3" >Green</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
<option value="6" selected="selected">White</option>
</select>
<br><br>
<div id="colorDiv" style="width:200px;height:50px;border:1px solid black;">
Change my color
</div>
</body>
</html>

How to set selected value in a Dropdownlist


In a Javascript combobox you can set a selected value as you wish.

Set selected value

When you click the button, you can see the color "Orange" is selected.

Source Code

<html>
<head>
<script type="text/javascript">
function changeSelection()
{
var eID = document.getElementById("colors");
eID.options[4].selected="true";
}
</script>
</head>
<body>
<select id="colors">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
</select>
<br><br>
<button onclick="changeSelection()">Set selected value</button>
</body>
</html>

Loop through all options in a dropdown list


var x = document.getElementById("colors");
for (var i = 0; i < x.length; i++)
{
alert(x.options[i].text);
}

How to remove an option from dropdownlist


var rmOption = document.getElementById("colors");
rmOption.options.remove(1);
Setting the Value of a text box based on the
value of a Select Box
Then update the tax when the province is changed.

Your inline onchange event on the HTML element limits you, and you currently have to pass lots of
stuff to it.
Instead of that, leave the select element just as a select element itself:

<form id="taxDetails" ...>


<select name="province">
...
</select>
...
</form>

And use scripting to attach the onchange event. The benefit of doing that is that the this keyword
now automatically refers to the element that triggered the event, and from there you can easily get to
the form, and other named elements of the form.

var form = document.getElementById('taxDetails');


form.elements.province.onchange = function () {
var form = this.form;
form.elements.showtax.value = taxCodes[this.value];
};

Here's a quick test page that demonstrates this in action.

<html>
<head>
</head>
<body>
<form id="taxDetails">
<select name="province" onchange="setTax(document.Form, this.value);">
<option value="">Select Province from List...</option>
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="ON">Ontario</option>
</select>
<input name="showtax" type="text" id="showtax" value="<show-value-of-tax-
here" />
</form>

<script>
var taxCodes = {
'AB': 5,
'BC': 12,
'ON': 13
};
var form = document.getElementById('taxDetails');
form.elements.province.onchange = function () {
var form = this.form;
form.elements.showtax.value = taxCodes[this.value];
};
</script>
</body>
</html>

PHP Login Form with Sessions


Session variables are used to store individual client’s information on the web
server for later use, as a web server does not know which client’s request to
be respond because HTTP address does not maintain state.

This tutorial enables you to create sessions in PHP via Login form and web
server respond according to his/her request.

To Start a PHP Session:

<?php

session_start();

// Do Something

?>

To Store values in PHP Session variable:


<?php

session_start();

// Store Session Data

$_SESSION['login_user']= $username; // Initializing Session with value of PHP Variable

To Read values of PHP Session variable:

<?php

session_start();

// Store Session Data

$_SESSION['login_user']= $username; // Initializing Session with value of PHP Variable

echo $_SESSION['login_user'];

To Unset or Destroy a PHP Session:

<?php

session_destroy(); // Is Used To Destroy All Sessions

//Or

if(isset($_SESSION['id']))

unset($_SESSION['id']); //Is Used To Destroy Specified Session

In our example, we have a login form when user fills up required fields and
press login button, a session will be created on server which assigns him a
unique ID and stores user information for later use.
Watch out live demo or download the given codes to use it.

DOWNLOAD SCRIPT LIVE DEMO

Complete HTML and PHP codes are given below.

PHP File: index.php


Given below code creates an HTML login form.
<?php

include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){

header("location: profile.php");

?>

<!DOCTYPE html>

<html>

<head>

<title>Login Form in PHP with Session</title>

<link href="style.css" rel="stylesheet" type="text/css">

</head>

<body>

<div id="main">

<h1>PHP Login Session Example</h1>

<div id="login">

<h2>Login Form</h2>

<form action="" method="post">

<label>UserName :</label>

<input id="name" name="username" placeholder="username" type="text">

<label>Password :</label>

<input id="password" name="password" placeholder="**********" type="password">

<input name="submit" type="submit" value=" Login ">

<span><?php echo $error; ?></span>

</form>

</div>

</div>
</body>

</html>

PHP File: login.php


Consists of login script in which PHP session is intialized.

<?php

session_start(); // Starting Session

$error=''; // Variable To Store Error Message

if (isset($_POST['submit'])) {

if (empty($_POST['username']) || empty($_POST['password'])) {

$error = "Username or Password is invalid";

else

// Define $username and $password

$username=$_POST['username'];

$password=$_POST['password'];

// Establishing Connection with Server by passing server_name, user_id and password as a


parameter

$connection = mysql_connect("localhost", "root", "");

// To protect MySQL injection for Security purpose

$username = stripslashes($username);

$password = stripslashes($password);

$username = mysql_real_escape_string($username);

$password = mysql_real_escape_string($password);

// Selecting Database

$db = mysql_select_db("company", $connection);


// SQL query to fetch information of registerd users and finds user match.

$query = mysql_query("select * from login where password='$password' AND


username='$username'", $connection);

$rows = mysql_num_rows($query);

if ($rows == 1) {

$_SESSION['login_user']=$username; // Initializing Session

header("location: profile.php"); // Redirecting To Other Page

} else {

$error = "Username or Password is invalid";

mysql_close($connection); // Closing Connection

?>

PHP File: profile.php


It is the redirected page on successful login.

<?php

include('session.php');

?>

<!DOCTYPE html>

<html>

<head>

<title>Your Home Page</title>

<link href="style.css" rel="stylesheet" type="text/css">

</head>

<body>
<div id="profile">

<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>

<b id="logout"><a href="logout.php">Log Out</a></b>

</div>

</body>

</html>

PHP File: session.php


This page, fetches complete information of the logged in user.

<?php

// Establishing Connection with Server by passing server_name, user_id and password as a


parameter

$connection = mysql_connect("localhost", "root", "");

// Selecting Database

$db = mysql_select_db("company", $connection);

session_start();// Starting Session

// Storing Session

$user_check=$_SESSION['login_user'];

// SQL Query To Fetch Complete Information Of User

$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);

$row = mysql_fetch_assoc($ses_sql);

$login_session =$row['username'];

if(!isset($login_session)){

mysql_close($connection); // Closing Connection

header('Location: index.php'); // Redirecting To Home Page

}
?>

PHP File: logout.php


To destroy all the sessions and redirecting to home page.

<?php

session_start();

if(session_destroy()) // Destroying All Sessions

header("Location: index.php"); // Redirecting To Home Page

?>

My SQL Code Segment:

To create database and table, execute following codes in your My SQL .

CREATE DATABASE company;

CREATE TABLE login(

id int(10) NOT NULL AUTO_INCREMENT,

username varchar(255) NOT NULL,

password varchar(255) NOT NULL,

PRIMARY KEY (id)

)
CSS File: style.css

Styling HTML elements.

@import http://fonts.googleapis.com/css?family=Raleway;

/*----------------------------------------------

CSS Settings For HTML Div ExactCenter

------------------------------------------------*/

#main {

width:960px;

margin:50px auto;

font-family:raleway

span {

color:red

h2 {

background-color:#FEFFED;

text-align:center;

border-radius:10px 10px 0 0;

margin:-10px -40px;

padding:15px

hr {

border:0;

border-bottom:1px solid #ccc;

margin:10px -40px;

margin-bottom:30px

}
#login {

width:300px;

float:left;

border-radius:10px;

font-family:raleway;

border:2px solid #ccc;

padding:10px 40px 25px;

margin-top:70px

input[type=text],input[type=password] {

width:99.5%;

padding:10px;

margin-top:8px;

border:1px solid #ccc;

padding-left:5px;

font-size:16px;

font-family:raleway

input[type=submit] {

width:100%;

background-color:#FFBC00;

color:#fff;

border:2px solid #FFCB00;

padding:10px;

font-size:20px;

cursor:pointer;

border-radius:5px;

margin-bottom:15px
}

#profile {

padding:50px;

border:1px dashed grey;

font-size:20px;

background-color:#DCE6F7

#logout {

float:right;

padding:5px;

border:dashed 1px gray

a {

text-decoration:none;

color:#6495ed

i {

color:#6495ed

Potrebbero piacerti anche