Sei sulla pagina 1di 162

AJAX ADD & RETRIEVE MYSQL

RECORDS USING JQUERY & PHP


FEBRUARY 15, 2013 BY AGUNG SETIAWAN
I love jQuery framework, feels like we can do some awesome things easily. If you are familiar
with the basic of jQuery framework too, the next thing you have to do is learn to use jQuery Ajax
to add and retrieve records from MySql database. Let’s take a look at how we implement real
time add and retrieve records using Ajax.
Database
sample database comment table columns id, name and message
1
+---------+--------------+------+-----+---------+----------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +---------+--------------+------+-----+---------+----------------+
4 | id | int(5) | NO | PRI | NULL | auto_increment |
5 | name | varchar(20) | NO | | NULL | |
| message | varchar(120) | NO | | NULL | |
6 +---------+--------------+------+-----+---------+----------------+
7
comment.php
1 <html>
2 <head>
3
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
4 <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script
5
6 <script type="text/javascript">
7 $(document).ready(function(){
8 $("#button").click(function(){
9
10 var name=$("#name").val();
var message=$("#message").val();
11
12 $.ajax({
13 type:"post",
14 url:"process.php",
15 data:"name="+name+"&message="+message,
success:function(data){
16 $("#info").html(data);
17 }
18
19 });
20
21 });
22 });
</script>
23 </head>
24
25 <body>
26 <form>
27 name : <input type="text" name="name" id="name"/>
28 </br>
message : <input type="text" name="message" id="message" />
29 </br>
30 <input type="button" value="Send Comment" id="button">
31
32 <div id="info" />
33 </form>
</body>
3 </html>
process.php
1
2 <?php
3 mysql_connect("localhost","root","");
4 mysql_select_db("php_databaseajax");
5
$name=$_POST["name"];
6 $message=$_POST["message"];
7
8 $query=mysql_query("INSERT INTO comment(name,message) values('$name','$message') ")
9
10 if($query){
11 echo "Your comment has been sent";
}
12 else{
13 echo "Error in sending your comment";
14 }
15 ?>
16
Try to input some comments using that form, here’s what i got

The record i just submitted is successfully added to the database. Although we can’t see right
now but it can be checked directly in your MySql.
1 +----+----------------+---------------------------+
2 | id | name | message |
3 +----+----------------+---------------------------+
4 | 1 | Agung Setiawan | Cool comment |
5 | 2 | Nusantara | Indonesia is hot but nice |
+----+----------------+---------------------------+
6
What is the value of the comment feature of web app if visitors can’t see their own comment.

Now, this is our time to be a hero…


Edit both files that we have created to add the ability to retrieve records from database.
comment.php
<html>
<head>

<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>


<script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script

<script type="text/javascript">
$(document).ready(function(){

function showComment(){
$.ajax({
type:"post",
url:"process.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}

showComment();

$("#button").click(function(){

var name=$("#name").val();
var message=$("#message").val();

$.ajax({
type:"post",
url:"process.php",
data:"name="+name+"&message="+message+"&action=addcomme
success:function(data){
showComment();

});

});
});
</script>
</head>

<body>
<form>
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Send Comment" id="button">

<div id="info" />


<ul id="comment"></ul>
</form>
</body>
</html>
process.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("php_databaseajax");

$action=$_POST["action"];

if($action=="showcomment"){
$show=mysql_query("Select * from comment order by id desc");

while($row=mysql_fetch_array($show)){
echo "<li><b>$row[name]</b> : $row[message]</li>";
}
}
else if($action=="addcomment"){
$name=$_POST["name"];
$message=$_POST["message"];

$query=mysql_query("INSERT INTO comment(name,message) values('$name','$message')

if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
}
?>

Now it is more cool with visitor’s comment directly show up after Send Button is clicked

AJAX JQUERY TUTORIAL, SIMPLE


YET POWERFUL
FEBRUARY 14, 2013 BY AGUNG SETIAWAN
Ajax jQuery Tutorial. Ajax is a programming technique that makes it possible to do data
change with the server in the background, so the web page doesn’t need to refresh in order to
change the page partially.
Here we go our hero again, jQuery!. By using jQuery, ajax development process is a lot easier.
In this tutorial we will learn how to implement Ajax using jQuery in our web pages. We will
create a project to better understanding the topic.

The Project
In this project we will create simple form submitting. Whenever users type their name in the
form an then submit it by clicking the submit button. Their name will be shown below the input
form without page refresh process :D. By Using this technique our web application is feels like
desktop application.
ajaxfirst.php
1
2
3 <html>
4 <head>
5
6 <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
7 <script type="text/javascript">
$(document).ready(function(){
8 $("#submit").click(function(){
9
10 var name=$("#name").val();
11 $.ajax({
12 type:"post",
13 url:"getname.php",
data:"name="+name,
14 success:function(data){
15 $("#info").html(data);
16 }
17 })
});
18 });
19 </script>
20 </head>
21
22 <body>
23 <form method="post" action="">
Name : <input type="text" name="name" id="name"/>
24 <input type="button" name="submit" id="submit" value="Submit"/>
25 </form>
26 <div id="info" />
27 </body>
</html>
28
29
30
and following code is responsible in giving the output that needs to be shown
getname.php
1 <?php
2
3 $name=$_POST["name"];
4 echo "Thank you ".$name." for Register in our site"
5
?>
6
Here is the result

Okay, so far we have learn the basic of Ajax using jQuery. In next cool tutorial we will learn
how to use this technique to be implemented in database application

Ajax Pagination Using jQuery,


PHP And MySQL
In this tutorial we will show you how to create ajax based pagination using
jQuery, PHP and MySQL.Now the user can load the records without page refresh
using ajax.You may also like Simple Pagination With PHP And MySQL
To Create Ajax Pagination It Takes Only Three Steps:-
1. Make a PHP file to display the records
2. Make a PHP file to get and send the records
3. Make a CSS file and define styling

Step 1.Make a PHP file to display the records


We make a PHP file and save it with a name pagination.php
// Database Structure
CREATE TABLE `language` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`language_name` text NOT NULL,
`language_description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

<html>
<head>
<link href="pagination_style.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function get_data(no)
{
$.ajax
({
type:'post',
url:'get_data.php',
data:{
row_no:no
},
success:function(response) {
document.getElementById("pagination_div").innerHTML=response;
}
});
}
</script>
</head>
<body>
<div id="wrapper">

<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$select =mysql_query("SELECT * FROM language");


$total_results=mysql_num_rows($select);
$row=mysql_fetch_array($select);
?>
<div id="pagination_div">
<p class="para1"><?php echo $row['language_name'];?></p>
<p class="para2"><?php echo $row['language_description'];?></p>
</div>

<div id="tota_page_div">
<?php
for($i=1;$i<=$total_results;$i++)
{
echo "<input type='button' value='".$i."' onclick='get_data(".$i.")'>";
}
?>
</div>

</div>
</body>
</html>

In this step we create a database table called 'language' and insert some rows in
it and then display the first row and also get total no of rows in our table to create
buttons for pagination to get data.We also create function get_data() which is
used to get data from our 'get_data.php' file and then display the data in our
'pagination_div'.You may also like Load Data From Database Without Page
Refresh Using Ajax.
Step 2.Make a PHP file to get and send the records
We make a PHP file and save it with a name get_data.php
<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

if(isset($_POST['row_no']))
{
$row=$_POST['row_no'];
$row=$row-1;
$select_data=mysql_query("select * from language limit $row,1");
$row=mysql_fetch_array($select_data);
echo "<p class='para1'>".$row['language_name']."</p>";
echo "<p class='para2'>".$row['language_description']."</p>";
exit();
}
?>

In this step we get the row_no val and subtract that value to 1 because in mysql
row indexing start with 0 so to get 1st row we have to pass 0 in limit clause and
we have to display 1 record each time so we use 1 in limit clause and after
quering the database we get the results and send back to 'pagination.php' for
display.Always validate data before and after sending the value.
Step 3.Make a CSS file and define styling
We make a CSS file and save it with a name pagination_style.css
body
{
text-align:center;
width:100%;
margin:0 auto;
padding:0px;
font-family:helvetica;
background-color:#D8D8D8;
}
#wrapper
{
text-align:center;
margin:0 auto;
padding:0px;
width:995px;
}
#pagination_div
{
border:1px solid;
margin-top:50px;
border:1px dashed #585858;
width:300px;
padding:10px;
box-sizing:border-box;
margin-left:350px;
min-height:180px;
}
#pagination_div p
{
margin:0px;
}
#pagination_div .para1
{
font-size:45px;
font-weight:bold;
color:#585858;
}
#pagination_div .para2
{
margin-top:20px;
font-size:25px;
font-weight:bold;
color:#585858;
}
#tota_page_div
{
margin-top:20px;
}
#tota_page_div input[type="button"]
{
background-color:#585858;
border:none;
margin:2px;
color:white;
height:35px;
width:35px;
border-radius:50%;
}

Thats all, this is create ajax pagination using jQuery, PHP and MySQL.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
Automatically Refresh HTML
page or div after specific time
Interval
There are several ways to refresh a complete HTML page after specific time interval, and same is the
case with any specific Div or Span or any HTML element on a page, that we can refresh any specific
part/element of HTML page without reloading the complete page.
First let’s take a look at refreshing HTML page after specific time interval, this can be achieved
using either JavaScript or by meta tags.
A) Using Javascript:

You can use either of the following scripts to refresh after every 5 secounds, say:

Code I:
1 <script>
2
3 function autoRefresh()
4 {
5 window.location = window.location.href;
6 }
7
8 setInterval('autoRefresh()', 5000); // this will reload page after every 5 secounds; Method I
9 </script>
OR

Code II:

1 <script>
2
3 function autoRefresh1()
4 {
5 window.location.reload();
6 }
7
8 setInterval('autoRefresh1()', 5000); // this will reload page after every 5 secounds; Method II
9 </script>
B) Refresh page using Meta tags

Its very easy, you just have to put a meta tag in head tag as follows:
1 <head>
2
3 <meta http-equiv="refresh" content="5" />
4 <!-- This will refresh page in every 5 seconds, change content= x to refresh page after x seconds -->
5 </head>
Refresh Div/Span on HTML page after specific time:

In this part we will use JQuery to perform the task, as its provides few of the best options that can
help us.
Suppose you have a div with ID as result similar to following:
1 <div id="result"></div>
Then JQuery code will be as follows:
1 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
2 <script>
3 function autoRefresh_div()
4 {
5 $("#result").load("load.html");// a function which will load data from other file after x seconds
6 }
7
8 setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
9 </script>
Similarly you can use $.ajax() or $.post() etc instead of load() function and put the response in a div
or a span.

— Automatically Refresh HTML page or div after specific time Interval —

Bootstrap Autocomplete with Dynamic


Data Load using PHP Ajax
In this tutorial, we are going to see how to load data dynamically for an
autocomplete suggestion list, Bootstrap Typeahead input field. I use jQuery
AJAX to call the PHP MySQL script to read the data from the database and
autocomplete dynamically. The loaded data will be returned to the source of
the Typeahead script to list the autocomplete suggestions.

In a previous tutorial, we have implemented the Bootstrap autocomplete with


local array data. In this example, it stores countries in a database table instead
of a Javascript array. The source of the typeahead function is read and
supplied from the database by using jQuery AJAX. I used AJAX to execute PHP
script by passing the Typeahead field input as the query parameter to process
the SELECT to get data for the autocomplete suggestion.

jQuery AJAX Callback to Supply Typeahead Source

The following jQuery script is used to initialize the Bootstrap Typeahead


function to implement autocomplete for an input field. While typing data to
the input field, the value is sent to the PHP script as the query parameter using
jQuery AJAX POST method. This method received the database response in a
JSON format and used as the source for showing autocomplete suggestions.

<script>

$(document).ready(function () {

$('#txtCountry').typeahead({

source: function (query, result) {

$.ajax({

url: "server.php",

data: 'query=' + query,

dataType: "json",

type: "POST",

success: function (data) {

result($.map(data,
function (item) {

return item;

}));

});
}

});

});

</script>

Dynamic Autocomplete using Database

The following PHP script receives the Typeahead input as the SELECT query
parameter. This will be bound to the query statement to get the related
country name that starts with the query string. This data will be encoded in
JSON format and return to the Typehead source attribute.

<?php

$keyword = strval($_POST['query']);

$search_param = "{$keyword}%";

$conn =new mysqli('localhost', 'root', '' ,


'blog_samples');

$sql = $conn->prepare("SELECT * FROM tbl_country WHERE


country_name LIKE ?");

$sql->bind_param("s",$search_param);

$sql->execute();

$result = $sql->get_result();

if ($result->num_rows > 0) {

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

$countryResult[] = $row["country_name"];

}
echo json_encode($countryResult);

$conn->close();

?>

Create, Edit And Delete File Using


PHP And HTML
In this tutorial we will show you how to create, edit and delete file using PHP and
HTML.By using these methods you can create any type of file, edit any file and
delete any file.You may also like add, edit and delete records using jQuery, PHP
and MySQl.
To Create, Edit And Delete File It Takes Only Two Steps:-
1. Make a HTML file and define markup
2. Make a PHP file to create, edit and delete file

Step 1.Make a HTML file and define markup


We make a HTML file and save it with a name file.html
<html>
<body>

<form method="post" action="file_operation.php" id="create_form">


<input type="text" name="file_name">
<input type="submit" value="Create File" name="create_file">
</form>

<form method="post" action="file_operation.php" id="edit_form">


<input type="text" name="file_name">
<textarea name="edit_text"></textarea>
<input type="submit" value="Edit File" name="edit_file">
</form>

<form method="post" action="file_operation.php" id="delete_form">


<input type="text" name="file_name">
<input type="submit" value="Delete File" name="delete_file">
</form>

</body>
</html>

In this step we create three forms to create, edit and delete file.In first form user
have to enter file name to create new file.In second form user have to enter file
name and text to add in that file.In third form user have to enter file name to
delete that file.You may also like delete multiple records from MySQL using PHP.

Step 2.Make a PHP file to create, edit and delete file


We make a PHP file and save it with a name file_operation.php
<?php
if(isset($_POST['create_file']))
{
$file_name=$_POST['file_name'];
$folder="files/";
$ext=".txt";
$file_name=$folder."".$file_name."".$ext;
$create_file = fopen($file_name, 'w');
fclose($create_file);
}

if(isset($_POST['edit_file']))
{
$file_name=$_POST['file_name'];
$write_text=$_POST['edit_text'];
$folder="files/";
$ext=".txt";
$file_name=$folder."".$file_name."".$ext;
$edit_file = fopen($file_name, 'w');

fwrite($edit_file, $write_text);
fclose($edit_file);
}

if(isset($_POST['delete_file']))
{
$file_name=$_POST['file_name'];
$folder="files/";
$ext=".txt";
$file_name=$folder."".$file_name."".$ext;
unlink($file_name);
}
?>

In this step we create three isset() function to do three different file operations
like create a file, edit existing file and delete a file.In first isset() function we get
file name entered by the user to create file with that name we specify '.txt' file
extension you can specify any extension or you can ask from user also then we
use fopen function to create file and then using fclose function to close that
file.See fopen is used for both purposes creating and editing a file.In third isset()
function we get file name to delete entered by the user then we use unlink
function to delete that file from folder.You may also like add,edit and delete rows
from table dynamically.
Css auto hide div after 5 seconds
han defining for each browser Jquery is better.

Hide Copy Code


$(document).ready(function () {

setTimeout(function() {
$('.success').slideUp("slow");
}, 5000);
});

Drag and Drop Reorder Images using


jQuery, Ajax, PHP & MySQL

Drag and Drop feature makes web page user-friendly and provides a nice User
Interface for the web application. jQuery UI provides an easy way to add draggable
functionality on DOM element. This tutorial shows you the uses of jQuery drag and
drop feature to sort the list elements.

If we want to control the display order of images in the list, image order needs to be
stored in the database. In this tutorial, we’ll provide a more interactive way to implement
the images reorder functionality. Here we’ll explain how to add jQuery drag and drop
feature to rearrange images order and save images display order to the MySQL
database. You can use this functionality for managing images gallery, managing users
list or any other useful place.

Our example script helps to implement dynamic drag and drop reorder images using
jQuery, Ajax, PHP and MySQL. Using our scripts you can also implement the drag and
drop reorder list, rows or sorting elements.

Before you begin, take a look at the folder and files structure to build drag and drop
reorder images functionality using jQuery, Ajax, PHP and MySQL.
 db.php

 orderUpdate.php

 index.php

 style.css

 images/

Database Table Creation

To store uploaded images information with display order, a table is required in MySQL
database. The following SQL creates images table with some basic required fields in

the database.

CREATE TABLE `images` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`img_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`img_order` int(5) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

DB Class (db.php)

The DB class handles all the database related works. Specify your database host
($dbHost), username ($dbUsername), password ($dbPassword), and name
($dbName). The DB class contains two methods to fetch and update images data.

 getRows() function fetch the images data from the database.

 updateOrder() function updates list order of the images.

<?php
class DB{
//database configuration
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "codexworld";
private $imgTbl = 'images';

function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this-
>dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}

function getRows(){
$query = $this->db->query("SELECT * FROM ".$this-
>imgTbl." ORDER BY img_order ASC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$result[] = $row;
}
}else{
$result = FALSE;
}
return $result;
}

function updateOrder($id_array){
$count = 1;
foreach ($id_array as $id){
$update = $this->db->query("UPDATE ".$this-
>imgTbl." SET img_order = $count WHERE id = $id");
$count ++;
}
return TRUE;
}
}
?>
Update Images Order (orderUpdate.php)

The order_update.php file receive the current images order from the index.php through

Ajax. The images IDs string breaks into array and pass to the DB class to update the
images reorder.

<?php
//include database class
include_once 'db.php';
$db = new DB();

//get images id and generate ids array


$idArray = explode(",",$_POST['ids']);

//update images order


$db->updateOrder($idArray);
?>

Reorder Images with Drag and Drop (index.php)

The index.php file display the images and allow the user to reorder images by drag and

drop.
JavaScript
Include the jQuery and jQuery UI library.

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>

The following jQuery codes are used to enable the jQuery sortable() features and

implement the drag & drop functionality. When save request is submitted by the user,
current images order send to the orderUpdate.php file using Ajax for update images

order.

<script>
$(document).ready(function(){
$('.reorder_link').on('click',function(){
$("ul.reorder-photos-list").sortable({ tolerance: 'pointer' });
$('.reorder_link').html('save reordering');
$('.reorder_link').attr("id","save_reorder");
$('#reorder-helper').slideDown('slow');
$('.image_link').attr("href","javascript:void(0);");
$('.image_link').css("cursor","move");
$("#save_reorder").click(function( e ){
if( !$("#save_reorder i").length ){
$(this).html('').prepend('<img src="images/refresh-
animated.gif"/>');
$("ul.reorder-photos-list").sortable('destroy');
$("#reorder-helper").html( "Reordering Photos - This could take a
moment. Please don't navigate away from this page."
).removeClass('light_box').addClass('notice notice_error');

var h = [];
$("ul.reorder-photos-list li").each(function() {
h.push($(this).attr('id').substr(9)); });

$.ajax({
type: "POST",
url: "orderUpdate.php",
data: {ids: " " + h + ""},
success: function(){
window.location.reload();
}
});
return false;
}
e.preventDefault();
});
});
});
</script>
PHP & HTML
Initially, all the images are listed from the database using PHP and DB class. Once the
reorder link is clicked, drag & drop feature is enabled for reorder.

<?php
//include database class
include_once 'db.php';
$db = new DB();
?>
<div>
<a href="javascript:void(0);" class="btn outlined mleft_no reorder_link"
id="save_reorder">reorder photos</a>
<div id="reorder-helper" class="light_box" style="display:none;">1. Drag
photos to reorder.<br>2. Click 'Save Reordering' when finished.</div>
<div class="gallery">
<ul class="reorder_ul reorder-photos-list">
<?php
//Fetch all images from database
$images = $db->getRows();
if(!empty($images)){
foreach($images as $row){
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-
handle"><a href="javascript:void(0);" style="float:none;" class="image_link"><img
src="images/<?php echo $row['img_name']; ?>" alt=""></a></li>
<?php } } ?>
</ul>
</div>
</div>

style.css

This file contains some CSS code, which is used to styling the image gallery and links.

.reorder_link {
color: #3675B4;
border: solid 2px #3675B4;
border-radius: 3px;
text-transform: uppercase;
background: #fff;
font-size: 18px;
padding: 10px 20px;
margin: 15px 15px 15px 0px;
font-weight: bold;
text-decoration: none;
transition: all 0.35s;
-moz-transition: all 0.35s;
-webkit-transition: all 0.35s;
-o-transition: all 0.35s;
white-space: nowrap;
}
.reorder_link:hover {
color: #fff;
border: solid 2px #3675B4;
background: #3675B4;
box-shadow: none;
}
#reorder-helper{margin: 18px 10px;padding: 10px;}
.light_box {
background: #efefef;
padding: 20px;
margin: 10px 0;
text-align: center;
font-size: 1.2em;
}

.gallery{ width:100%; float:left; margin-top:100px;}


.gallery ul{ margin:0; padding:0; list-style-type:none;}
.gallery ul li{ padding:7px; border:2px solid #ccc; float:left; margin:10px 7px;
background:none; width:auto; height:auto;}
.gallery img{ width:250px;}
/* NOTICE */
.notice, .notice a{ color: #fff !important; }
.notice { z-index: 8888; }
.notice a { font-weight: bold; }
.notice_error { background: #E46360; }
.notice_success { background: #657E3F; }

DYNAMIC DEPENDENT SELECT BOX


USING JQUERY AND AJAX
FEBRUARY 19, 2013 BY AGUNG SETIAWAN
Dynamic Dependent Select Box means whenever there is selected value in the “parent” box, the
“child” box will fit its options value according to the value of “parent” box. It can be illustrated
like this. Say, we have “country” select box and “city” select box. If we choose “Indonesia” in
the “country” select box, the “city” select box will only show some cities located in Indonesia
like “Jakarta”,”Semarang” and “Bandung”. It won’t show “Sydney”,”Amsterdam”,”Hamburg”
and so on.
In This tutorial we are gonna make simple application to perform Dynamic Dependent Select
Box.

Database Structure
This database consists of two tables, country and city
country table
1 +-------+-------------+------+-----+---------+---------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +-------+-------------+------+-----+---------+---------------+
4 | id | int(5) | NO | PRI | NULL |auto_increment |
5 | name | varchar(30) | NO | | NULL | |
+-------+-------------+------+-----+---------+---------------+
6
city table
1
+------------+-------------+------+-----+---------+----------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +------------+-------------+------+-----+---------+----------------+
4 | id | int(5) | NO | PRI | NULL | auto_increment |
5 | name | varchar(30) | NO | | NULL | |
| id_country | int(5) | NO | MUL | NULL | |
6 +------------+-------------+------+-----+---------+----------------+
7
and this is table relationship that needs to be connected in our sample Dynamic Dependent Select
Box

selectbox.php
This PHP file is used as an html form and also execute client side programming, which is jQuery
to perform dynamic dependent select box
<html>
1 <head>
2 <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
3 <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script
4
5 <script type="text/javascript">
6 $(document).ready(function(){
7
8
$("#country").change(function(){
9 var country=$("#country").val();
10 $.ajax({
11 type:"post",
12 url:"getcity.php",
13 data:"country="+country,
success:function(data){
14 $("#city").html(data);
15 }
16 });
17 });
});
18 </script>
19 </head>
20 <body>
21 Country :
22 <select name="country" id="country">
<option>-select your country-</option>
23 <?php
24 include "db.php";
25 $result=mysql_query("SELECT id,name from country order by name");
26 while($country=mysql_fetch_array($result)){
27
echo "<option value=$country[id]>$country[name]</option>";
28
29
} ?>
30 </select>
31
32
33 City :
34 <select name="city" id="city">
<option>-select your city-</option>
35 </select>
36 </body>
37 </html>
38
39
40
41
42
43
44
getcity.php
1
<?php
2 include "db.php";
3
4 $country=$_POST["country"];
5 $result=mysql_query("select id,name FROM city where id_country='$country' ");
6 while($city=mysql_fetch_array($result)){
7 echo"<option value=$city[id]>$city[name]</option>";
8
}
9 ?>
10
db.php
1 <?php
2 mysql_connect("localhost","root","");
3 mysql_select_db("php_dependentselectbox");
4 ?>
Screenshot
Dynamic Star Rating with PHP and
jQuery
In this PHP tutorial, we are going to list database records and add a dynamic
star rating to those records by using jQuery star rating script. We are having a
group of stars for each database record. When we add the rating to a record,
an AJAX call will be sent store the current rating to the database.

Display Star Rating for Database Results

This PHP code is for reading Database results and adding stars for each.

<?php

require_once("dbcontroller.php");

$db_handle = new DBController();

$query ="SELECT * FROM tutorial";

$result = $db_handle->runQuery($query);

if(!empty($result)) {

foreach ($result as $tutorial) {

?>

<tr>

<td valign="top">

<div class="feed_title"><?php echo $tutorial["title"]; ?></div>

<div id="tutorial-<?php echo $tutorial["id"]; ?>">

<input type="hidden" name="rating" id="rating" value="<?php


echo $tutorial["rating"]; ?>" />

<ul onMouseOut="resetRating(<?php echo $tutorial["id"]; ?>);">


<?php

for($i=1;$i<=5;$i++) {

$selected = "";

if(!empty($tutorial["rating"]) && $i<=$tutorial["rating"]) {

$selected = "selected";

?>

<li class='<?php echo $selected; ?>'


onmouseover="highlightStar(this,<?php echo $tutorial["id"];
?>);" onmouseout="removeHighlight(<?php echo $tutorial["id"];
?>);" onClick="addRating(this,<?php echo $tutorial["id"];
?>);">★</li>

<?php } ?>

<ul>

</div>

<div><?php echo $tutorial["description"]; ?></div>

</td>

</tr>

<?php }} ?>

jQuery Functions to Store Rating

In this example code, we have same four jQuery functions. But, we have added
additional code for calling PHP via AJAX on clicking rating stars. And also, we
have added database row id reference to the “li” selectors for the unique
identification of the rating. The functions are,
function highlightStar(obj,id) {

removeHighlight(id);

$('.demo-table #tutorial-'+id+'
li').each(function(index) {

$(this).addClass('highlight');

if(index == $('.demo-table #tutorial-'+id+'


li').index(obj)) {

return false;

});

function removeHighlight(id) {

$('.demo-table #tutorial-'+id+'
li').removeClass('selected');

$('.demo-table #tutorial-'+id+'
li').removeClass('highlight');

function addRating(obj,id) {

$('.demo-table #tutorial-'+id+'
li').each(function(index) {

$(this).addClass('selected');

$('#tutorial-'+id+' #rating').val((index+1));
if(index == $('.demo-table #tutorial-'+id+'
li').index(obj)) {

return false;

});

$.ajax({

url: "add_rating.php",

data:'id='+id+'&rating='+$('#tutorial-'+id+'
#rating').val(),

type: "POST"

});

function resetRating(id) {

if($('#tutorial-'+id+' #rating').val() != 0) {

$('.demo-table #tutorial-'+id+'
li').each(function(index) {

$(this).addClass('selected');

if((index+1) == $('#tutorial-'+id+'
#rating').val()) {

return false;

});

}
}

PHP MySQL Star Rating Update via AJAX

This PHP code will be executed via an AJAX request. This code runs an update
query by receiving id and current rating from AJAX.

<?php

if(!empty($_POST["rating"]) && !empty($_POST["id"])) {

require_once("dbcontroller.php");

$db_handle = new DBController();

$query ="UPDATE tutorial SET rating='" .


$_POST["rating"] . "' WHERE id='" . $_POST["id"] . "'";

$result = $db_handle->updateQuery($query);

?>

Dynamically Add Input Fields And


Submit To Database With jQuery and
PHP
Previously I wrote about adding dynamic input fields in a webpage using jQuery, I got a
lot of queries on how to submit it to database. This tutorial is all about generating input
fields on the fly in a web page and submitting the entered data into database. For this
tutorial let’s assume you have a registration or survey page which asks user to enter his
hobbies (hobbies can be multiple). Some have two hobbies and some may have ten, so
we will let them enter as many hobbies they want. You can use this tutorial to build
more user friendly forms which collect data from users. Let your users create fields on
the fly and enter data.
I have created a sample database “hobbies” having one table “my_hobbies”. Here is
the sql query to generate hobbies table:

SQL query for hobbies table:

1 &lt;/p&gt;

2 <span id="IL_AD7" class="IL_AD">CREATE TABLE</span> IF NOT EXISTS


<code>my_hobbies</code> (
3 <code>id</code> int(10) NOT NULL AUTO_INCREMENT,
4 <code>hobbies</code> varchar(20) NOT NULL,
5 PRIMARY KEY (<code>id</code>)
6)

To connect with database I have created a separate “dbconn.php” file which contains
hostname, mysql username and mysql password to connect with database.

Code for dbconn.php:

1 </p>
2 <?php
3 $mysql_db_hostname = "localhost";
4 $mysql_db_user = "root";
5 $mysql_db_password = "12345";
6 $mysql_db_database = "dynamicfield";
7
$connection =
8 mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die(
"Could not connect database");

9 mysql_select_db($mysql_db_database, $connection) or die("Could not select


database");
10 ?>

Our main index.php file contains jQuery and PHP code to submit data into database.
To retrieve data entered in newly generated field I have used array “dynfield[]” and
then using for each loop pass the retrieved data into sql query.

Code for index.php:


1 </p>
2 <?php
3 require("dbconn.php");
4 ?>
5
6 <html>
7 <head>
8 <title></title>
9 <script type="text/javascript" src="jquery.js"></script>
10 <script type="text/javascript">
11 var counter = 0;
12 $(function(){
13 $('p#add_field').click(function(){
14 counter += 1;
15 $('#container').<span id="IL_AD4" class="IL_AD">append</span>(
16 '<strong>Hobby No. ' + counter + '</strong><br />'

+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text"


17
/><br />' );
18
19 });
20 });
21 </script>
22
23 <body>
24
25 <?php
26 if (isset($_POST['submit_val'])) {
27 if ($_POST['dynfields']) {
28 foreach ( $_POST['dynfields'] as $key=>$value ) {
29 $values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES
30
('$values')", $connection );
31
32 }
33 }
34

35 echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies


Added</h2></i>";
36
37 mysql_close();
38 }
39 ?>
40 <?php if (!isset($_POST['submit_val'])) { ?>
41 <h1>Add your Hobbies</h1>
42 <form method="post" action="">
43
44 <div id="container">
45 <p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p>
46 </div>
47
48 <input type="submit" name="submit_val" value="Submit" />
49 </form>
50 <?php } ?>
51
52 </body>
53 </html>

You can use this code in your projects and share this tutorial among your friends. A lot
can be done in this code like validation of fields and validation of entered data. Different
type of fields like drop down, radio buttons etc can be added in the same way.

FORM VALIDATION USING JQUERY


VALIDATION PLUGIN
MARCH 10, 2013 BY AGUNG SETIAWAN

Jquery Validation is a powerful jQuery plugin to perform form validation in client side. Why
we choose client side validation?, because this approach is more lightweight since no request is
sent to the server. We need 2 JavaScript files to make jquery validation, first the core of jquery
and the second is the plugin it self.
1
2
3
4 <body>
5 <form id="formMahasiswa" method="post">
6 <table>
<tr>
7 <td>Nama</td>
8 <td><input type="text" name="nama" id="nama" class="required"/></td>
9 <td><label for="nama" class="error"></label></td>
10 </tr>
11 <tr>
<td>Nim</td>
12 <td><input type="text" name="nim" id="nim" class="required" /></td>
13 <td><label for="nim" class="error"></label></td>
14 </tr>
15 <tr>
16 <td>Alamat</td>
<td><input type="text" name="alamat" id="alamat" class="required" /></td>
17 <td><label for="alamat" class="error"></label></td>
18 </tr>
19 <tr>
20 <td>Agama</td>
<td><input type="text" name="agama" id="agama" class="required" /></td>
21 <td><label for="agama" class="error"></label></td>
22 </tr>
23 <tr>
24 <td>Jenis Kelamin</td>
25 <td><input type="radio" name="jenis_kelamin" id="jenis_kelamin" value="Laki-L
<input type="radio" name="jenis_kelamin" id="jenis_kelamin" value="Peremp
26 </td>
27 <td><label for="jenis_kelamin" class="error"></label></td>
28 </tr>
29 <tr>
<td></td>
30 <td><input type="submit" value="Submit"/></td>
31 </tr>
32 </table>
33 </form>
34 </body>
35
36
37
Note at line 6 and 7. We add class=”required” to every input that needs to be validated. We also
add label refers to input element to show the error message.
here is the script to do validation, simple enough
1 <script type="text/javascript">
2 $(document).ready(function(){
3 $("#formMahasiswa").validate();
4 });
</script>
5
Next, we create css styling to make the error messages colored in red.
1 <style type="text/css">
2 .error{
3 color: red;
4 }
</style>
5
Now try to submit the form without typing anything in the input elements. Here’s what we get

As we can see from image above, the error messages are still in default format. We can
customize by adding title attribute on input elements.
1 <td><input type="text" name="nama" id="nama" class="required" title="Nama Harus Diisi"/>

Jquery Validation plugin can be used for all types of inputs such as checkboxes, text areas, select
and others. We can also perform more complex validation like input must have 5-10 characters
long, must be email, must be a Url and etc.

Generate QR Code Using PHP


And HTML
QR code is also known as Quick Response code it is a 2D barcode format code
it is used to store text like phone numbers, emails, address and simple text etc.In
this tutorial we will show you how to generate QR code using PHP and
HTML.You have to download PHP QR Code Library to generate QR code.You
may also like generate barcode using PHP

To Generate QR Code It Takes Only Two Steps:-


1. Make a HTML file to send text
2. Make a PHP file to generate QR code

Step 1.Make a HTML file to send text


We make a HTML file and save it with a name qrcode.html
<html>
<body>
<div id="wrapper">
<form method="post" action="generate_code.php">
<input type="text" name="qr_text">
<input type="submit" name="generate_text" value="Generate">
</form>
</div>
</body>
</html>

In this step we create a form to send text entered by the user to storing the text
and generating QR code.

Step 2.Make a PHP file to generate QR code


We make a PHP file and save it with a name generate_code.php
<?php
if(isset($_POST['generate_text']))
{
include('phpqrcode/qrlib.php');
$text=$_POST['qr_text'];
$folder="images/";
$file_name="qr.png";
$file_name=$folder.$file_name;
QRcode::png($text,$file_name);
echo"<img src='images/qr.png'>";

//To Display Code Without Storing


QRcode::png($text);
}
?>

In this step we get text entered by the user to store in QR code and then we
include qrlib.php file which is the main file to generate code then we specify
folder in which we were going to store QR code as a image and give a name to
that image then we use QRcode::png() predefined function to generate QR code.

That's all, this is how to generate QR code using PHP and HTML.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.

HOW TO CREATE AJAX SEARCH USING


PHP JQUERY AND MYSQL
Ajax Search. I love ajax very much. I have expressed my feeling by writing tutorial about
ajax here, here, here and here. This tutorial shows how to create ajax search form using
PHP, Jquery and Mysql. When you click the search button or press enter key the results
will be displayed on the same page and without refresh page process. This is very
interesting and simple. Take a look at beautiful live demo.

Here we use database of wordpress, wp_posts table is used.

HTML Page Ajax Search

We create an input text and button to facilitate users to search tutorials. Also we create
a list to display the search results.
1
<body>
2 <div id="container">

3 <input type="text" id="search" placeholder="Search Tutorials Here... Ex: Ja

4 <input type="button" id="button" value="Search" />

5 <ul id="result"></ul>

</div>
6
</body>
7
JavaScript

We specify so that when users click button or press enter key the process of searching
data begins. Here we use click and keyup event. As usual we use ajax function to
perform data change in the background.
To limit when users input nothing but click the button or press enter, we create simple
checking using if.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/j
1
<script type="text/javascript">
2
$(document).ready(function(){
3

4
function search(){
5

6
var title=$("#search").val();
7

8
if(title!=""){
9 $("#result").html("<img alt="ajax search" src='ajax-loader.gi

10 $.ajax({

11 type:"post",

12 url:"search.php",

data:"title="+title,
13
success:function(data){
14
$("#result").html(data);
15
$("#search").val("");
16
}
17
});
18 }

19

20

21
22 }

23

24 $("#button").click(function(){

search();
25
});
26

27
$('#search').keyup(function(e) {
28
if(e.keyCode == 13) {
29
search();
30
}
31 });

32 });

33 </script>

34

35

36

PHP Code

Database configuration file used in this tutorial. Adjust the server location, username,
password and database name
file : db.php
1 <?php

2 mysql_connect("localhost","user","password") or die("error koneksi");

3 mysql_select_db("database_name") or die("error pilih db");

4 ?>

This is the code that searchs articles based on the user input and brings the results
in ajax searchway.Once again we performs checking using if to ensure when no data
found it will give an output “No Tutorial Found”
file : search.php
1 <?php
2 include "db.php";

4 $title=$_POST["title"];

6
$result=mysql_query("SELECT * FROM wp_posts where post_title like '%$title%' and pos
7
$found=mysql_num_rows($result);
8

9
if($found>0){
10
while($row=mysql_fetch_array($result)){
11
echo "<li>$row[post_title]</br>
12
<a href=$row[guid]>$row[guid]</a></li>";
13 }

14 }else{

15 echo "<li>No Tutorial Found<li>";

16 }

// ajax search
17
?>
18

19

Css

<style type="text/css">

#container{

width:800px;

margin:0 auto;

}
#search{

width:700px;

padding:10px;

#button{

display: block;

width: 100px;

height:30px;

border:solid #366FEB 1px;

background: #91B2FA;

ul{

margin-left:-40px;

ul li{

list-style-type: none;

border-bottom: dotted 1px black;

height: 50px;

li:hover{

background: #A592E8;

}
a{

text-decoration: none;

font-size: 18px;

</style>

How to Pass PHP Array to JavaScript


Function
By: CodexWorldLast Updated: Oct 5, 2017
ShareTweet

The json_encode() function in PHP provides an easy way to pass an array to


JavaScript. Using json_encode() function, you can pass both single dimentional and
multidimentional array to the JavaScript function.

The following example code shows you how to pass PHP array to JavaScript
using json_encode() function.

The $phpArray variable holds a multidimensional PHP array which needs to pass to
JavaScript.

<?php
$phpArray = array(
array('name'=>'John Doe', 'email'=>'john@gmail.com'),
array('name'=>'Merry Moe', 'email'=>'merry@gmail.com')
);
?>

The PHP json_encode() function is used to pass array to JavaScript function.

getUserInfo(<?php echo json_encode($phpArray); ?>)


Now the PHP array can be accessed as a JavaScript object and you can use it in the
JavaScript code.

function getUserInfo(userObj){
alert(userObj[0].name);
}

Image Resize Using PHP Before


Uploading
Image manipulation is always be one of the most difficult task for a programmer.
Because images are need to small and beautiful after manipulation and this
takes time and good programming knowledge.

But nowadays, PHP make this very simple you can do any kind of image
manipulation you want with the help of its GD Library. In this tutorial we will
show you an easy and quick way to PHP image resize before uploading it to the
server.

Before we start you have the knowledge of how to upload image to the server if
you dont know please see our php image uploadtutorial and then start.

There are many other libraries which are also used for image manipulation like
Imagick, jQuery Plugins etc.
You can manipulate the image in just two simple steps:-
1. Make a HTML form to upload the image
2. Recieve The Image And Manipulate

Step 1.Make a HTML form


We make a HTML form with post method and save it with a
name upload_form.html
<html>
<body>

<form method="POST" action="getdata.php" enctype="multipart/form-data">


<input type="file" name="image1">
<input type="submit" name="upload_image" value="Upload">
</form>

</body>
</html>

You can do javascript form validation to make your code more secure.We submit
the data from this HTML form to resize_image.phpwhere we do image
manipulation.

Step 2.Recieve The Image And Manipulate


In this step we get the image and then resize.
<?php

$upload_image = $_FILES[" image1 "][ "name" ];

$folder = "/xampp/htdocs/images/";

move_uploaded_file($_FILES[" image1 "][" tmp_name "], "$folder".$_FILES[" image1 "]["


name "]);

$file = '/xampp/htdocs/images/'.$_FILES[" image1 "][" name "];


We have to save image in the directory first and then we do image manipulation.
You can use any path of directory from where you want to save the image.You
may also like jquery image resize.
$uploadimage = $folder.$_FILES[" image1 "][" name "];
$newname = $_FILES[" image1 "][" name "];

// Set the resize_image name


$resize_image = $folder.$newname."_resize.jpg";
$actual_image = $folder.$newname.".jpg";

// It gets the size of the image


list( $width,$height ) = getimagesize( $uploadimage );

// It makes the new image width of 350


$newwidth = 350;

// It makes the new image height of 350


$newheight = 350;

// It loads the images we use jpeg function you can use any function like
imagecreatefromjpeg
$thumb = imagecreatetruecolor( $newwidth, $newheight );
$source = imagecreatefromjpeg( $resize_image );

// Resize the $thumb image.


imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width,
$height);
// It then save the new image to the location specified by $resize_image variable

imagejpeg( $thumb, $resize_image, 100 );

// 100 Represents the quality of an image you can set and ant number in place of 100.
Default quality is 75

$out_image=addslashes(file_get_contents($resize_image));

// After that you can insert the path of the resized image into the database

mysql_connect(' localhost ' , root ,' ' );


mysql_select_db(' image_database ');
$insertquery = " insert into resize_images values('1,$out_image') ";
$result = mysql_query( $insertquery );

?>

For more details and PHP image manipulations functions you can learn from this
site.

That's all, this is how to do image resize using PHP before uploading with the
help of PHP GD Library, HTML and MySQL.

You can customize this code further as per your requirement. And please feel
free to give comments on this tutorial.

LIVE USERNAME AVAILABILITY


CHECKING USING AJAX AND JQUERY
FEBRUARY 17, 2013 BY AGUNG SETIAWAN
Live Username Availability Checking using Ajax and jQuery. Username and password is
widely used in any modern web site right now. Username is unique, it must be different with
others. Therefore, we as developers have to write a code to check whether a username is already
been taken or not yet.
I wrote simple code to do live check username availability using jQuery and Ajax.Live means
you don’t need to click the submit button then send username into another code that returns
availability of username. You can customize the code to better suit your need.

Table Structure
1 +----------+-------------+------+-----+---------+-------+
2 | Field | Type | Null | Key | Default | Extra |
3 +----------+-------------+------+-----+---------+-------+
4 | username | varchar(50) | NO | PRI | NULL | |
5 | password | varchar(32) | NO | | NULL | |
+----------+-------------+------+-----+---------+-------+
6
username.php
this is the html form and jQuery function
1 <html>
2 <head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
3 <!-- <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></s
4
5 <script type="text/javascript">
6
7 $(document).ready(function(){
8 $("#username").change(function(){
9 $("#message").html("<img src='ajax-loader.gif' /> checking...");
10
11
var username=$("#username").val();
12
13 $.ajax({
14 type:"post",
15 url:"check.php",
16 data:"username="+username,
17 success:function(data){
if(data==0){
18 $("#message").html("<img src='tick.png' /> Username availa
19 }
20 else{
21 $("#message").html("<img src='cross.png' /> Username alrea
}
22 }
23 });
24
25 });
26
27 });
28
29 </script>
30 </head>
31
<body>
32
33 <table>
34 <tr>
35 <td>Username</td>
36 <td>:</td>
<td><input type="text" name="username" id="username"/><td>
37 <td id="message"><td>
38 </tr>
39
40 <tr>
41 <td>Password</td>
42 <td>:</td>
<td><input type="text" name="password" id="password" /><td>
43 </tr>
44 </table>
45 </body>
46 </html>
47
48
49
50
51
52
53
check.php
1
<?php
2
3 mysql_connect("localhost","root","");
4 mysql_select_db("php_usernamelivecheck");
5
6 $username=$_POST["username"];
7 $query=mysql_query("SELECT * from user where username='$username' ");
8
9 $find=mysql_num_rows($query);
10
echo $find;
11
12 ?>
13
Try to type some letters in the username text field and then change focus of the cursor on the
password field. Checking is on the way

If the username you wrote is not yet registered, the system will tell you that it is available to be
used.

However if you pick up username that have been registered the system will tell you too

Load Data From Database Without


Page Refresh Using Ajax and
jQuery.
To Load the data from database without page refresh it takes only two
steps:-
1. Make a HTML form to load the data
2. Connect to the database and send data

Step 1.Make a HTML form to load the data


We make a HTML form with post method and save it with a
name displaydata.html
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

function loaddata()
{
var name=document.getElementById( "username" );

if(name)
{
$.ajax({
type: 'post',
url: 'loaddata.php',
data: {
user_name:name,
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
$( '#display_info' ).html(response);
}
});
}

else
{
$( '#display_info' ).html("Please Enter Some Words");
}
}

</script>

</head>
<body>

<input type="text" name="username" id="username" onkeyup="loaddata();">


<div id="display_info" >
</div>

</body>
</html>

You can do validation to make your code more secure or you can view our How
to do validation before and after submitting the formtutorial.

Step 2.Connect To The Database and Send Data


In this step we connect to our sample database named student and it has a table
named student_info which has 3 columns name,age,course and then we query
the database and get desired results.
// loaddata.php

<?php

if( isset( $_POST['user_name'] ) )


{

$name = $_POST['user_name'];
$host = 'localhost';
$user = 'root';
$pass = ' ';

mysql_connect($host, $user, $pass);

mysql_select_db('student');

$selectdata = " SELECT age,course FROM student_info WHERE name LIKE '$name%' ";

$query = mysql_query($selectdata);

while($row = mysql_fetch_array($query))
{
echo "<p>".$row['age']."</p>";
echo "<p>".$row['course']."</p>";
}

}
?>

Whatever this page echo's it display on the displaydata.html page.You can also
view load more results from database using ajax.

That's all, this is how to load data from database without page refresh using Ajax
and jQuery.You can customize this code further as per your requirement. And
please feel free to give comments on this tutorial.

PHP AUTOCOMPLETE TUTORIAL


USING JQUERY
FEBRUARY 13, 2013 BY AGUNG SETIAWAN

Autocomplete Php is a cool technic you should learn to make your website or you web
application looks cool and also user friendly. As you might have known, autocomplete gives a
user a list of nearly same data with what he or she is looking for.
In this tutorial we will learn together about how to use this technic in our sample web app using
PHP and JQuery. Before we go to the tutorial, first we make a list of our need to build this app.

Our application will only have one page, that is a form where user try to input a data. In this form
the magic happens. When user inputs data, an autocomplete will show up to help him/her fulfill
the form. We will create 2 PHP files, one for the form and one that is responsible in supplying
data into an autocomplete. We also have a database with a table named “student” that has 2
columns, “id” and “name”.
Now, let’s make our hand dirty by writing the code :D. Prepare your self!
First we make our database tabel. Here is the structure of our “student” tabel
1 +-------+-------------+------+-----+---------+----------------+
2 | Field | Type | Null | Key | Default | Extra |
3 +-------+-------------+------+-----+---------+----------------+
4 | id | int(5) | NO | PRI | NULL | auto_increment |
5 | name | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
6
Next we make our main form page.
autocomplete.php
1 <html>
2 <head>
3 <script type="text/javascript"
4 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></scrip
<script type="text/javascript"
5 src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js">
6 <link rel="stylesheet" type="text/css"
7 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui
8
9 <script type="text/javascript">
$(document).ready(function(){
10 $("#name").autocomplete({
11 source:'getautocomplete.php',
12 minLength:1
13 });
14 });
</script>
15 </head>
16
17 <body>
18
19 <form method="post" action="">
20 Name : <input type="text" id="name" name="name" />
</form>
21
22
23 </body>
24 <html>
25
26
27
note that we bind the “name” which is the id of the text input into jquery function
in $(“#name”). In autocomplete function inside jquery, we use two
properties, source and minLength. Source is the file that supplies our data to be shown in
autocomplete. minLength is used to specify the number of character a user has to type to activate
the auto completion.
Now we make our “supplier” file.
getautocomplete.php
1
2 <?php
3 mysql_connect("localhost","root","");
4 mysql_select_db("php_autocomplete");
5
$term=$_GET["term"];
6
7 $query=mysql_query("SELECT * FROM student where name like '%".$term."%' order by nam
8 $json=array();
9
10 while($student=mysql_fetch_array($query)){
11 $json[]=array(
12 'value'=> $student["name"],
'label'=>$student["name"]." - ".$student["id"]
13 );
14 }
15
16 echo json_encode($json);
17
18 ?>
19
That code should be easy to understand. The things you have to get attention are the $json array
values, ‘value’ and ‘label’. ‘value’ is as the value of the input text, where ‘label’ is used as label
text in auto complete. You will know what i mean later.
Now insert some data to your database as a sample. Then navigate your browser to
localhost/yourprojectname/getautocomplete.php
you should see the data in json format

don’t worry about the warning text, it’s only because we didn’t supply the variable with a value.
Try to make some changes by navigating your browser to
localhost/yourprojectname/getautocomplete.php?term=whatyouwanttosearch
Change the whatyouwanttosearch with some name of students and now you should

understand
Now is the time to test our app. Go to
localhost/yourprojectname/autocomplete.php>
and type some letters. Here’s what i got

What you see in pop up auto complete is “label” we talked about some mintues ago. Click one of
those data and what inside text input is “value” we talked above.
PHP CRUD Operations without Page
Refresh using jQuery Ajax MySQL
CRUD stands for Create, Read, Update and Delete database records. Add, Edit,
Update, and Delete functionality is used almost every web project in PHP. You’ve done
it many times, but today we’ll show you the more user-friendly way to implement CRUD
functionality in PHP.

Here we’ll implement PHP CRUD operations without page refresh using jQuery, Ajax,
and MySQL. The functionality of the example script would be read, add, update, and
delete the records from MySQL database.

In this example script, we’ll fetch the users data from the database and display the user
data list with add link, edit link, and delete link. By these links user can add new data to
the database, update previously inserted data and delete the data from the database.
All operations will happen on a single page without page refresh. Also, bootstrap table
structure will be used for styling the list, form fields, and links.

Let’s start the step-by-step guide on creating a CRUD application with PHP using
jQuery Ajax MySQL. Before you begin, take a look at the files structure of CRUD
application.

Database Table Creation

For this example script, we’ll create a simple table ( users ) with some basic columns

where users data would be stored.

CREATE TABLE `users` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1' COMMENT
'1=Active, 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Class ( DB.php )

DB class handles all the operations related to the database. For example, connect with
the database, insert, update and delete record from the database. You need to change
the $dbHost , $dbUsername , $dbPassword , and $dbName variables value as per the

database credentials.

<?php
/*
* DB Class
* This class is used for database related (connect, insert, update, and delete)
operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class DB{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "codexworld";

public function __construct(){


if(!$this->db){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this-
>dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}

/*
* Returns rows from the database based on the conditions
* @param string name of the table
* @param array select, where, order_by, limit and return_type conditions
*/
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}

if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}

if(array_key_exists("start",$conditions) && array_key_exists("limit",$con


ditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit
",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}

$result = $this->db->query($sql);

if(array_key_exists("return_type",$conditions) && $conditions['return_typ


e'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
$data = '';
}
}else{
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
return !empty($data)?$data:false;
}

/*
* Insert data into the database
* @param string name of the table
* @param array the data for inserting into the table
*/
public function insert($table,$data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$val."'";
$i++;
}
$query = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")"
;
$insert = $this->db->query($query);
return $insert?$this->db->insert_id:false;
}else{
return false;
}
}

/*
* Update data into the database
* @param string name of the table
* @param array the data for updating into the table
* @param array where condition on updating data
*/
public function update($table,$data,$conditions){
if(!empty($data) && is_array($data)){
$colvalSet = '';
$whereSql = '';
$i = 0;
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$colvalSet .= $pre.$key."='".$val."'";
$i++;
}
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$query = "UPDATE ".$table." SET ".$colvalSet.$whereSql;
$update = $this->db->query($query);
return $update?$this->db->affected_rows:false;
}else{
return false;
}
}

/*
* Delete data from the database
* @param string name of the table
* @param array where condition on deleting data
*/
public function delete($table,$conditions){
$whereSql = '';
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$query = "DELETE FROM ".$table.$whereSql;
$delete = $this->db->query($query);
return $delete?true:false;
}
}

userAction.php

This file handles the requests coming from the view file ( index.php ) and returns the

respective requested data. Here the code is executed based on


the action_type . action_type can be five types, data , view , add , edit , and delete .
The following operations can happen based on the action_type .
 data returns the single user data based on the id as JSON format.

 view returns all the users data as HTML format.

 add insert the record in the database and return the status.

 edit updates the record in the database and returns the status.

 delete deletes the record from the database and returns the status.

<?php
include 'DB.php';
$db = new DB();
$tblName = 'users';
if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
if($_POST['action_type'] == 'data'){
$conditions['where'] = array('id'=>$_POST['id']);
$conditions['return_type'] = 'single';
$user = $db->getRows($tblName,$conditions);
echo json_encode($user);
}elseif($_POST['action_type'] == 'view'){
$users = $db->getRows($tblName,array('order_by'=>'id DESC'));
if(!empty($users)){
$count = 0;
foreach($users as $user): $count++;
echo '<tr>';
echo '<td>#'.$count.'</td>';
echo '<td>'.$user['name'].'</td>';
echo '<td>'.$user['email'].'</td>';
echo '<td>'.$user['phone'].'</td>';
echo '<td><a href="javascript:void(0);" class="glyphicon glyphico
n-
edit" onclick="editUser(\''.$user['id'].'\')"></a><a href="javascript:void(0);" c
lass="glyphicon glyphicon-
trash" onclick="return confirm(\'Are you sure to delete data?\')?userAction(\'del
ete\',\''.$user['id'].'\'):false;"></a></td>';
echo '</tr>';
endforeach;
}else{
echo '<tr><td colspan="5">No user(s) found......</td></tr>';
}
}elseif($_POST['action_type'] == 'add'){
$userData = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
$insert = $db->insert($tblName,$userData);
echo $insert?'ok':'err';
}elseif($_POST['action_type'] == 'edit'){
if(!empty($_POST['id'])){
$userData = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
$condition = array('id' => $_POST['id']);
$update = $db->update($tblName,$userData,$condition);
echo $update?'ok':'err';
}
}elseif($_POST['action_type'] == 'delete'){
if(!empty($_POST['id'])){
$condition = array('id' => $_POST['id']);
$delete = $db->delete($tblName,$condition);
echo $delete?'ok':'err';
}
}
exit;
}

index.php

This is the main view file which is visible to the user. In this single page, the user can do
all the CRUD operations. For better understanding we’ve divided this script into two
parts.

Bootstrap & JavaScript:


Bootstrap CSS & JS library and jQuery library need to be included for work this script
smoothly. You can omit Bootstrap CSS & JS library if you don’t want to use bootstrap
table structure.

<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script
>

getUsers() function is used to get the users data from the userAction.php file using

ajax and render the received HTML in the user data list.
function getUsers(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}

userAction() function is used to send add, edit, and delete request to

the userAction.php file using ajax and give the response to the user.

function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData =
$("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
url: 'userAction.php',
data: userData,
success:function(msg){
if(msg == 'ok'){
alert('User data has been '+statusArr[type]+' successfully.');
getUsers();
$('.form')[0].reset();
$('.formData').slideUp();
}else{
alert('Some problem occurred, please try again.');
}
}
});
}

editUser() function is used to get the particular user data from the userAction.php file

and set the respective value in the edit form fields.

function editUser(id){
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'userAction.php',
data: 'action_type=data&id='+id,
success:function(data){
$('#idEdit').val(data.id);
$('#nameEdit').val(data.name);
$('#emailEdit').val(data.email);
$('#phoneEdit').val(data.phone);
$('#editForm').slideDown();
}
});
}

HTML:
Initially already inserted users data is fetched from the users table and listed with edit &
delete links. At the top of the user list, add link would be displayed. The add and edit
form HTMl would be visible if add or edit link is clicked.
<div class="container">
<div class="row">
<div class="panel panel-default users-content">
<div class="panel-heading">Users <a href="javascript:void(0);"
class="glyphicon glyphicon-plus" id="addLink"
onclick="javascript:$('#addForm').slideToggle();">Add</a></div>
<div class="panel-body none formData" id="addForm">
<h2 id="actionLabel">Add User</h2>
<form class="form" id="userForm">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name"
id="name"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email"
id="email"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" name="phone"
id="phone"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning"
onclick="$('#addForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success"
onclick="userAction('add')">Add User</a>
</form>
</div>
<div class="panel-body none formData" id="editForm">
<h2 id="actionLabel">Edit User</h2>
<form class="form" id="userForm">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name"
id="nameEdit"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email"
id="emailEdit"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" name="phone"
id="phoneEdit"/>
</div>
<input type="hidden" class="form-control" name="id"
id="idEdit"/>
<a href="javascript:void(0);" class="btn btn-warning"
onclick="$('#editForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success"
onclick="userAction('edit')">Update User</a>
</form>
</div>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userData">
<?php
include 'DB.php';
$db = new DB();
$users = $db-
>getRows('users',array('order_by'=>'id DESC'));
if(!empty($users)): $count = 0; foreach($users as $user):
$count++;
?>
<tr>
<td><?php echo '#'.$count; ?></td>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
<td><?php echo $user['phone']; ?></td>
<td>
<a href="javascript:void(0);" class="glyphicon
glyphicon-edit" onclick="editUser('<?php echo $user['id']; ?>')"></a>
<a href="javascript:void(0);" class="glyphicon
glyphicon-trash" onclick="return confirm('Are you sure to delete
data?')?userAction('delete','<?php echo $user['id']; ?>'):false;"></a>
</td>
</tr>
<?php endforeach; else: ?>
<tr><td colspan="5">No user(s) found......</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>

CSS:
CSS for .none class is required and the other CSS is optional.

/* required style*/
.none{display: none;}

/* optional styles */
table tr th, table tr td{font-size: 1.2rem;}
.row{ margin:20px 20px 20px 20px;width: 100%;}
.glyphicon{font-size: 20px;}
.glyphicon-plus{float: right;}
a.glyphicon{text-decoration: none;}
a.glyphicon-trash{margin-left: 10px;}

Conclusion

In this tutorial, we’re trying to make PHP CRUD operations more simple and user-
friendly. You can share your thought to improve this script or the DB class.

PHP MySQL CRUD (Create,


Read, Update, Delete) Operations
using jQuery
PHP MySQL CRUD is all about INSERT, UPDATE, DELETE and SELECT SQL queries using
PHP , it will help beginners to know about PHP and MySQL operations.

Live Demo

Note: Don’t use this script into your live projects, the motive of the script is to just provide basic
ideas to the beginners for learning, if you want to use this feature in the live projects then you
should focus on following points:

 Prevent your script from SQL Injections


 Use PDO extension or other DBAL/ORM’s like Laravel Eloquent or Doctrine.

Tutorial Features:
1. Insert records into MySQL Database
2. Read the records from Database and list
3. Update the record
4. Delete the record.

Technologies Used:
1. HTML
2. PHP with MySQL
3. jQuery
4. Bootstrap
5. CSS
6. JSON
Before starting let’s download basic lib files needed : ( if you already having this lib files you
can use your existing files )

 Download jQuery JS file from – http://jquery.com/download/


 Download Bootstrap from – http://getbootstrap.com/getting-started/#download ( Use basic Compiled
and minified files don’t go for Source code for now)
Let’s start of creating our demo web application to learn CRUD operations, first thing we are
going see is to create a database and tables required. ( if you have your database ready in mysql
go ahead and create tables using following sql code) I am assuming that you have database
created and ready to use.

Create MySQL Database and required Table:


users table

1 CREATE TABLE `test`.`users` (

2 `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,

3 `first_name` VARCHAR( 40 ) NOT NULL ,

4 `last_name` VARCHAR( 40 ) NOT NULL ,

5 `email` VARCHAR( 50 ) NOT NULL

6 ) ENGINE = MYISAM ;

Take a note: test.users – where test is the database name and users is a table name.
Users Table Structure

Basic Structure of Index.php:


Create index.php file and include basic files for jQuery and Bootstrap as showing below:

1 <!DOCTYPE html>

2 <html lang="en">

3 <head>

4 <meta charset="UTF-8">

5 <title>PHP and MySQL CRUD Operations Demo</title>

7 <!-- Bootstrap CSS File -->

8 <link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css" />

9 </head>

10 <body>

11

12 <!-- Content Section -->

13
14 <!-- /Content Section -->

15

16 <!-- Jquery JS file -->

17 <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>

18

19 <!-- Bootstrap JS file -->

20 <script type="text/javascript" src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>

21

22 <!-- Custom JS file -->

23 <script type="text/javascript" src="js/script.js"></script>

24 </body>

25 </html>

So we have our basic file ready to go, now let’s add button to open add new record popup along
with basic formatting like to have page heading and record container, refer following code:

1 <!-- Content Section -->

2 <div class="container">

3 <div class="row">

4 <div class="col-md-12">

5 <h2>PHP and MySQL CRUD Operations</h2>

6 <div class="pull-right">

7 <button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Record</button>

8 </div>

9 </div>

10 </div>

11 <div class="row">
12 <div class="col-md-12">

13 <h4>Records:</h4>

14 <div class="records_content"></div>

15 </div>

16 </div>

17 </div>

18 <!-- /Content Section -->

The above code is actually part of our index.php file, if you look at it, you will notice we have
application heading and Add New Record button which
refers to add_new_record_modal modal popup. we also have records_content div, this div
is going to display the data rendering from Ajax, we are going to see that next.
Now we need to add modal popup, we are using bootstrap modal popups here, go a head and use
following code to include popup in the index.php page.

If you’re not familiar with Bootstrap no worries you just need to copy this code later on you can
read about it, so now go ahead and add below modal to you index.php page.

1
<!-- Bootstrap Modal - To Add New Record -->
2
<!-- Modal -->
3
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
4
<div class="modal-dialog" role="document">
5
<div class="modal-content">
6
<div class="modal-header">
7
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">&times;</span></button>
8
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
9
</div>
10
<div class="modal-body">
11
12

13 <div class="form-group">

14 <label for="first_name">First Name</label>

15 <input type="text" id="first_name" placeholder="First Name" class="form-control" />

16 </div>

17

18 <div class="form-group">

19 <label for="last_name">Last Name</label>

20 <input type="text" id="last_name" placeholder="Last Name" class="form-control" />

21 </div>

22

23 <div class="form-group">

24 <label for="email">Email Address</label>

25 <input type="text" id="email" placeholder="Email Address" class="form-control" />

26 </div>

27

28 </div>

29 <div class="modal-footer">

30 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

31 <button type="button" class="btn btn-primary" onclick="addRecord()">Add Record</button>

32 </div>

33 </div>

34 </div>

</div>

If you notice in the above code we have popup called add_new_record_modal which includes
different input field in the ‘modal-body’ tag. so we have first name, last name and email address
here.
modal-footer – that’s the important part of the popup to call action such as addRecord, we
have button with JS method call with onclick event.
let’s save index.page page and try to load on browser.
Index.php Page:

Add New Record Popup:

Next Step is to create Add New Record and Read Records feature.

We have seen the basic setup of our application now we are going to look at the CREATE and
READ operation. That is also called as INSERT and SELECT operation in MySQL, basically to
create new record in the table.

It’s time to code jQuery plus JavaScript:


Handling Add New Records Action:
Let’s create our custom JS file called script.js file under JS folder and add following code:

js/script.js

1 // Add Record

2 function addRecord() {

3 // get values

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

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

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

8 // Add record

9 $.post("ajax/addRecord.php", {

10 first_name: first_name,

11 last_name: last_name,

12 email: email

13 }, function (data, status) {

14 // close the popup

15 $("#add_new_record_modal").modal("hide");

16

17 // read records again

18 readRecords();

19

20 // clear fields from the popup

21 $("#first_name").val("");
22 $("#last_name").val("");

23 $("#email").val("");

24 });

25 }

26

27 // READ records

28 function readRecords() {

29 $.get("ajax/readRecords.php", {}, function (data, status) {

30 $(".records_content").html(data);

31 });

32 }

If you notice in the above code, we have addRecord() function which is doing following
operation: Get the Values from the input fields and send it to addRecord.php file using Ajax call.
After that it’s closing the popup and reading records using readRecords() that is next function
to it.

PHP Script to Add New Record into the database:


Create ajax/addRecord.php file and use following code:

1 <?php

2 if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email']))

3 {

4 // include Database connection file

5 include("db_connection.php");

7 // get values

8 $first_name = $_POST['first_name'];

9 $last_name = $_POST['last_name'];
10 $email = $_POST['email'];

11

12 $query = "INSERT INTO users(first_name, last_name, email) VALUES('$first_name', '$last_name', '$email')";

13 if (!$result = mysqli_query($con, $query)) {

14 exit(mysqli_error($con));

15 }

16 echo "1 Record Added!";

17 }

18 ?>

Process: Accept the values from the POST variablea and insert record into the database.

PHP Script to Read existing Records from the Database:


Create ajax/readRecord.php file and use following code:

1 <?php

2 // include Database connection file

3 include("db_connection.php");

5 // Design initial table header

6 $data = '<table class="table table-bordered table-striped">

7 <tr>

8 <th>No.</th>

9 <th>First Name</th>

10 <th>Last Name</th>

11 <th>Email Address</th>

12 <th>Update</th>
13 <th>Delete</th>

14 </tr>';

15

16 $query = "SELECT * FROM users";

17

18 if (!$result = mysqli_query($con, $query)) {

19 exit(mysqli_error($con));

20 }

21

22 // if query results contains rows then featch those rows

23 if(mysqli_num_rows($result) > 0)

24 {

25 $number = 1;

26 while($row = mysqli_fetch_assoc($result))

27 {

28 $data .= '<tr>

29 <td>'.$number.'</td>

30 <td>'.$row['first_name'].'</td>

31 <td>'.$row['last_name'].'</td>

32 <td>'.$row['email'].'</td>

33 <td>

34 <button onclick="GetUserDetails('.$row['id'].')" class="btn btn-warning">Update</button>

35 </td>

36 <td>

37 <button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>

38 </td>

39 </tr>';

40 $number++;

41 }
42 }

43 else

44 {

45 // records now found

46 $data .= '<tr><td colspan="6">Records not found!</td></tr>';

47 }

48

49 $data .= '</table>';

50

51 echo $data;

52 ?>

In both files above I have included the db_connection.php file using php include()function,
this files is use to define our database connection string. It is better practice to add repetitive code
in the separate file, let’s create the file.

PHP to MysqL Database Connection Script:


Create ajax/db_connection.php file.
Note: Make change in the connection file according to your server configuration. (Host,
Username, Password and Database name)

1 <?php

3 // Connection variables

4 $host = "localhost"; // MySQL host name eg. localhost

5 $user = "root"; // MySQL user. eg. root ( if your on localserver)

6 $password = ""; // MySQL user password (if password is not set for your root user then keep it empty )

7 $database = "test_db"; // MySQL Database name

8
9 // Connect to MySQL Database

10 $con = new mysqli($host, $user, $password, $database);

11

12 // Check connection

13 if ($con->connect_error) {

14 die("Connection failed: " . $con->connect_error);

15 }

16

17 ?>

Test the application: try to add new record, you will need to be able to add the record and have it
listed, have a look on below screen shoot I have added few dummy records:

Fill the fields and click on Add Record button:

Add New Test Record


Dummy Records List

Handling Read Event on Page Load:


Whenever we load the page we needs to have our existing records to be list on the page right? So
go ahead ad added following code in to the script.js file and try to page again.

1 $(document).ready(function () {

2 // READ recods on page load

3 readRecords(); // calling function

4 });

Are you Good so far?


Handling Delete Action:
So now have we have our CREATE and READ feature is ready and tested, let’s go to next step and
add DELETE and UPDATE feature as well.
Add DeleteUser() function in the custom scrip.js file:

1 function DeleteUser(id) {

2 var conf = confirm("Are you sure, do you really want to delete User?");

3 if (conf == true) {

4 $.post("ajax/deleteUser.php", {

5 id: id

6 },

7 function (data, status) {

8 // reload Users by using readRecords();

9 readRecords();

10 }

11 );

12 }

13 }

PHP Script to Delete existing record from the database:


Create ajax/deleteUser.php file and add following code:

1 <?php

2 // check request
3 if(isset($_POST['id']) && isset($_POST['id']) != "")

4 {

5 // include Database connection file

6 include("db_connection.php");

8 // get user id

9 $user_id = $_POST['id'];

10

11 // delete User

12 $query = "DELETE FROM users WHERE id = '$user_id'";

13 if (!$result = mysqli_query($con, $query)) {

14 exit(mysqli_error($con));

15 }

16 }

17 ?>

UPDATE Feature
How does it work?

Let me explain in the step:

1. User clicks on update button from the list


2. Popup open up with the existing details field in
3. User can click on Save Changes button to update and save the records.
Get back to the code, so add required modal popup to update the record.

Go ahead and use the following html code and add to the index.php page, next to the existing
modal popup.
1
<!-- Modal - Update User details -->
2
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
3
<div class="modal-dialog" role="document">
4
<div class="modal-content">
5
<div class="modal-header">
6
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">&times;</span></button>
7
<h4 class="modal-title" id="myModalLabel">Update</h4>
8
</div>
9
<div class="modal-body">
10

11
<div class="form-group">
12
<label for="update_first_name">First Name</label>
13
<input type="text" id="update_first_name" placeholder="First Name" class="form-control"/>
14
</div>
15

16
<div class="form-group">
17
<label for="update_last_name">Last Name</label>
18
<input type="text" id="update_last_name" placeholder="Last Name" class="form-control"/>
19
</div>
20

21
<div class="form-group">
22
<label for="update_email">Email Address</label>
23
<input type="text" id="update_email" placeholder="Email Address" class="form-control"/>
24
</div>
25
26

27 </div>

28 <div class="modal-footer">

29 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

30 <button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>

31 <input type="hidden" id="hidden_user_id">

32 </div>

33 </div>

34 </div>

35 </div>

<!-- // Modal -->

Handling Existing User Details API:


Add getUserDetails() function in to the script.js file:
This function is used to read the existing user details and fill input fields from modal popup and
open it up.

1 function GetUserDetails(id) {

2 // Add User ID to the hidden field for furture usage

3 $("#hidden_user_id").val(id);

4 $.post("ajax/readUserDetails.php", {

5 id: id

6 },

7 function (data, status) {

8 // PARSE json data

9 var user = JSON.parse(data);


10 // Assing existing values to the modal popup fields

11 $("#update_first_name").val(user.first_name);

12 $("#update_last_name").val(user.last_name);

13 $("#update_email").val(user.email);

14 }

15 );

16 // Open modal popup

17 $("#update_user_modal").modal("show");

18 }

PHP Script to Fetch existing user details from the database:


Create ajax/readUserDetails.php file:

1 <?php

2 // include Database connection file

3 include("db_connection.php");

5 // check request

6 if(isset($_POST['id']) && isset($_POST['id']) != "")

7 {

8 // get User ID

9 $user_id = $_POST['id'];

10

11 // Get User Details

12 $query = "SELECT * FROM users WHERE id = '$user_id'";

13 if (!$result = mysqli_query($con, $query)) {

14 exit(mysqli_error($con));
15 }

16 $response = array();

17 if(mysqli_num_rows($result) > 0) {

18 while ($row = mysqli_fetch_assoc($result)) {

19 $response = $row;

20 }

21 }

22 else

23 {

24 $response['status'] = 200;

25 $response['message'] = "Data not found!";

26 }

27 // display JSON data

28 echo json_encode($response);

29 }

30 else

31 {

32 $response['status'] = 200;

33 $response['message'] = "Invalid Request!";

34 }

Update Action:
Add another JS function called UpdateUserDetails() in to the script.js file:

1 function UpdateUserDetails() {

2 // get values

3 var first_name = $("#update_first_name").val();


4 var last_name = $("#update_last_name").val();

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

7 // get hidden field value

8 var id = $("#hidden_user_id").val();

10 // Update the details by requesting to the server using ajax

11 $.post("ajax/updateUserDetails.php", {

12 id: id,

13 first_name: first_name,

14 last_name: last_name,

15 email: email

16 },

17 function (data, status) {

18 // hide modal popup

19 $("#update_user_modal").modal("hide");

20 // reload Users by using readRecords();

21 readRecords();

22 }

23 );

24 }

PHP Script to Update Existing Record:


Create ajax/updateUserDetails.php file:

1 <?php

2 // include Database connection file


3 include("db_connection.php");

5 // check request

6 if(isset($_POST))

7 {

8 // get values

9 $id = $_POST['id'];

10 $first_name = $_POST['first_name'];

11 $last_name = $_POST['last_name'];

12 $email = $_POST['email'];

13

14 // Updaste User details

15 $query = "UPDATE users SET first_name = '$first_name', last_name = '$last_name', email = '$email' WHERE id = '$id'";

16 if (!$result = mysqli_query($con, $query)) {

17 exit(mysqli_error($con));

18 }

19 }

Folder Structure:

Folder Structure
Complete Source code of script.js file:
1 // Add Record

2 function addRecord() {

3 // get values

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

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

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

8 // Add record

9 $.post("ajax/addRecord.php", {

10 first_name: first_name,

11 last_name: last_name,

12 email: email

13 }, function (data, status) {

14 // close the popup

15 $("#add_new_record_modal").modal("hide");

16

17 // read records again

18 readRecords();

19

20 // clear fields from the popup

21 $("#first_name").val("");

22 $("#last_name").val("");

23 $("#email").val("");

24 });

25 }

26

27 // READ records

28 function readRecords() {

29 $.get("ajax/readRecords.php", {}, function (data, status) {


30 $(".records_content").html(data);

31 });

32 }

33

34

35 function DeleteUser(id) {

36 var conf = confirm("Are you sure, do you really want to delete User?");

37 if (conf == true) {

38 $.post("ajax/deleteUser.php", {

39 id: id

40 },

41 function (data, status) {

42 // reload Users by using readRecords();

43 readRecords();

44 }

45 );

46 }

47 }

48

49 function GetUserDetails(id) {

50 // Add User ID to the hidden field for furture usage

51 $("#hidden_user_id").val(id);

52 $.post("ajax/readUserDetails.php", {

53 id: id

54 },

55 function (data, status) {

56 // PARSE json data

57 var user = JSON.parse(data);

58 // Assing existing values to the modal popup fields


59 $("#update_first_name").val(user.first_name);

60 $("#update_last_name").val(user.last_name);

61 $("#update_email").val(user.email);

62 }

63 );

64 // Open modal popup

65 $("#update_user_modal").modal("show");

66 }

67

68 function UpdateUserDetails() {

69 // get values

70 var first_name = $("#update_first_name").val();

71 var last_name = $("#update_last_name").val();

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

73

74 // get hidden field value

75 var id = $("#hidden_user_id").val();

76

77 // Update the details by requesting to the server using ajax

78 $.post("ajax/updateUserDetails.php", {

79 id: id,

80 first_name: first_name,

81 last_name: last_name,

82 email: email

83 },

84 function (data, status) {

85 // hide modal popup

86 $("#update_user_modal").modal("hide");

87 // reload Users by using readRecords();


88 readRecords();

89 }

90 );

91 }

92

93 $(document).ready(function () {

94 // READ recods on page load

95 readRecords(); // calling function

96 });

Complete Source code of index.php file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP and MySQL CRUD

1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>PHP and MySQL CRUD Operations Demo</title>
6
7 <!-- Bootstrap CSS File -->
8 <link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css"/>
9 </head>
10 <body>
11
12 <!-- Content Section -->
13 <div class="container">
14 <div class="row">
15 <div class="col-md-12">
16 <h1>Demo: PHP and MySQL CRUD Operations using Jquery</h1>
17 </div>
18 </div>
19 <div class="row">
20 <div class="col-md-12">
21 <div class="pull-right">
22 <button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Record</button>
23 </div>
24 </div>
25 </div>
26 <div class="row">
27 <div class="col-md-12">
28 <h3>Records:</h3>
29
30 <div class="records_content"></div>
31 </div>
32 </div>
33 </div>
34 <!-- /Content Section -->
35
36
37 <!-- Bootstrap Modals -->
38 <!-- Modal - Add New Record/User -->
39 <div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
40 <div class="modal-dialog" role="document">
41 <div class="modal-content">
42 <div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">

<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" id="first_name" placeholder="First Name" class="form-control"/>
</div>

Read And Delete File From Folder


Using PHP
To Read And Delete File From Folder It Takes Only Two Steps:-
1. Make a PHP file to read file from folder
2. Make a PHP file to delete file from folder

Step 1.Make a PHP file to read file from folder


We make a PHP file and save it with a name read.php
<html>
<body>
<div id="wrapper">

<div id="file_div">
<?php
$folder = "images/";
if ($dir = opendir($folder))
{
while (($file = readdir($dir)) !== false)
{
echo "<p>".$file."</p>";
echo "<form method='post' action='delete_file.php'>";
echo "<input type='hidden' name='file_name' value='".$file."'>";
echo "<input type='submit' name='delete_file' value='Delete File'>";
echo "</form>";
}
closedir($dir);
}
?>
</div>

</div>
</body>
</html>

In this step we read all the files from images folder and create a delete button for
each file to delete that file from folder.We use opendir() function to open the
folder for file reading and then use while() loop and readdir() function to read all
the files and then we use closedir() function to close the directory.You may also
like remove file extension using htaccess.

Step 2.Make a PHP file to delete file from folder


We make a PHP file and save it with a name delete_file.php
<?php
if(isset($_POST['delete_file']))
{
$filename = $_POST['file_name'];
unlink('images/'.$filename);
}
?>
In this step we get the file name and use php unlink() function to delete that file
from folder.

That's all, this is how to read and delete file from folder using PHP.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.

Read HTML From Text File Using


PHP
To Read HTML From Text File It Takes Only Two Steps:-
1. Make a Text file and add some HTML code for reading
2. Make a PHP file to read HTML content from a text file

Step 1.Make a Text file and add some HTML code for reading
We make a Text file and save it with a name content.text
<h1>Sample Text File</h1>
<p>This is used by our PHP file to read HTML content</p>
<br>
<table align=center>
<tr>
<td>Suresh</td><td>PHP Developer</td>
</tr>
<tr>
<td>Pooja</td><td>Web Designer</td>
</tr>
<tr>
<td>Amit</td><td>HTML Developer</td>
</tr>
<tr>
<td>Ram</td><td>Data Analyst</td>
</tr>
</table>

In this step we create a text file and write some HTML content for reading.You
can also add inline styling to your HTML code to display content in style.You may
also like read and write csv file using PHP.

Step 2.Make a PHP file to read HTML content from a text file
We make a PHP file and save it with a name read_html.php
<html>
<body>
<div id="wrapper">

<?php
$myfile = fopen("content.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("content.txt"));
fclose($myfile);
?>

</div>
</body>
</html>

In this step we use PHP fopen function to open our 'content.txt' file in read mode
and then use fread() function to display file content.You may also like read and
delete file from folder using PHP.
That's all, this is how to read HTML content from text file using PHP .You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.

Show Button On Hover Using


HTML And CSS
To Show Button On Hover It Takes Only Two Steps:-
1. Make a HTML file and define markup
2. Make a CSS file and define styling

Step 1.Make a HTML file and define markup


We make a HTML file and save it with a name show_button.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="button_style.css">
</head>
<body>
<div id="wrapper">
<div id="image_div">

<p class="img_wrapper">
<img src="images/image1.jpg">
<span><input type="button" value="PLAY"></span>
</p>

<p class="img_wrapper">
<img src="images/image2.jpg">
<span><input type="button" value="PAUSE"></span>
</p>
<p class="img_wrapper">
<img src="images/image3.jpg">
<span><input type="button" value="RESUME"></span>
</p>

</div>
</div>
</body>
</html>

In this step we add three images and then create three buttons to show.We use
images because we want to show button when user hover on images you can
use anything you want in place of images and wrap both image and button in <p>
tag it is must to have a container for image and button other wise your button will
not going to be show over image. You may also like enable disable submit button
using jQuery.

Step 2.Make a CSS file and define styling


We make a CSS file and save it with a name button_style.css
body
{
text-align:center;
width:995px;
margin:0 auto;
padding:0px;
font-family: "Myriad Pro","Helvetica Neue",Helvetica,Arial,Sans-Serif;
background-color:#E0F2F7;
}
#wrapper
{
margin:0 auto;
padding:0px;
text-align:center;
width:995px;
}
#wrapper h1
{
margin-top:150px;
font-size:55px;
color:#0489B1;
}
#wrapper h1 a
{
color:#0489B1;
font-size:18px;
}
#image_div .img_wrapper
{
width:180px;
position:relative;
display:inline-block;
}
#image_div .img_wrapper img
{
width:100%;
}
#image_div .img_wrapper:hover img
{
-webkit-filter: blur(1.7px);
}
#image_div .img_wrapper span
{
display:none;
position:absolute;
top:40px;
left:30px;
}
#image_div .img_wrapper:hover span
{
display:table-cell;
}
#image_div .img_wrapper span input[type="button"]
{
width:120px;
height:40px;
background-color:#00BFFF;
border:none;
color:white;
font-weight:bold;
font-size:17px;
}

In this step we use simple styling to show button over image when user hover on
image. One of the most important thing we use is position:relative in
img_wrapper and position:absolute in span so that our button will be shown
inside the image container. You may also like display text over image.

That's all, this is how to show button on hover using HTML and CSS.You can
customize this code further as per your requirement. And please feel free to give
comments on this tutorial.
Simple And Best Delete
Confirmation Message Using
jQuery HTML And CSS.
To Create Delete Confirmation Message It Takes Two steps:-
1. Make a HTML file and write markup and script for Delete Confirmation
Message
2. Make a CSS file and define styling for Delete Confirmation Message

Step 1.Make a HTML file and write markup and script for Delete
Confirmation Message
We make a HTML file and save it with a name message.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="message_style.css">
<script type="text/javascript" src="jquery.js">
<script type="text/javascript">

$(document).ready(function(){
$("#test_delete").click(function(){
message();
});
$("#cancel").click(function(){
hide();
});
});

function message()
{
$("#delete_message").slideDown();
}
function hide()
{
$("#delete_message").slideUp();
}
</script>

</head>

<body>

<div id="delete_message">
<h2>Are You Sure You Want To Delete This</h2>
<input type="button" value="Delete" id="delete">
<input type="button" value="Cancel" id="cancel">
</div>

<h1>Simple And Best Delete Confirmation Message Using jQuery,HTML And CSS</h1>
<center>
<input type="button" id="test_delete" value="Click To Test Delete Confirmation
Message">
</center>

</body>
</html>

In this step we make a confirmation message div which is hidden and on this we
made two buttons both are just for testing purpose and we make a third button to
show the confirmation message.We use
jQuery slideUp(); and slideDown(); functions for showing and hiding message
with animation you can use any kind of effect.You may also like simple
notification bar using jQuery.
Step 2.Make a CSS file and define styling for Delete Confirmation Message
We make a CSS file and save it with name message_style.css.
body
{
margin:0px;
padding:0px;
background-color:#E6E6E6;
font-family:helvetica;
}
#delete_message
{
display:none;
position:fixed;
top:0px;
width:100%;
height:150px;
background-color:#5882FA;
text-align:center;
}
#delete_message h2
{
color:#0431B4;
}
#delete,#cancel
{
border:none;
background:none;
width:100px;
height:40px;
font-size:18px;
border-radius:5px;
border:2px solid white;
margin:10px;
color:#CED8F6;
}
h1
{
text-align:center;
margin-top:200px;
color:#819FF7;
width:600px;
margin-left:200px;
}
#test_delete
{
border:none;
background:none;
width:400px;
height:50px;
font-size:18px;
border-radius:5px;
border:2px solid #819FF7;
margin:10px;
color:#045FB4;
}

Thats all, this is how to Create a Delete Confirmation Message Using


jQuery,HTML and CSS. You can customize this code further as per your
requirement. And please feel free to give comments on this tutorial.

Simple And Best Pagination With


PHP, MySQL
Steps For Creating PHP Pagination With MySQL
1. Connect To Database.
2. Query The MySQL Database.
3. Get The Results.

Step 1.Connect To Database


In this step we have to create a sample database and table for our pagination
and connect to database table so that we can implement pagination technique.

You can connect to any existing database from which you want to get the data. In
this step we use sample database named "demo".
<?php
$host = 'localhost';
$user = 'root';
$pass = '';

mysql_connect($host, $user, $pass);

mysql_select_db('demo');
?>

Step 2.Query The MySQL Database.


<?php
$offset = 0;
$page_result = 5;

if($_GET['pageno'])
{
$page_value = $_GET['pageno'];
if($page_value > 1)
{
$offset = ($page_value - 1) * $page_result;
}
}

$select_results = " select * from student_info limit $offset, $page_result ";


?>

In second step we use three php variables $offset, $page_result, $page_value.


$offset = 0 because we want to select the data from the first that is 0th position
from the table, $page_result = 5 because we want to display 5 results at a time.

$page_value = $_GET['pageno'] it is the value of the page when the user wants
to change the page and click the pagination page number. Then if the
$page_value is greater than 1 we change the $offset value to the value of this
code ($page_value - 1) * $page_result.

Then we query the database we select details from student_info table and limit
the results returned by the query for more details of limit clause visit our MySQL
clause tutorial.You may also like load more results from database using ajax.

Step 3.Get The Results.


<?php

$result = mysql_query( $select_results );

while($row = mysql_fetch_array($result))
{
echo $row[' student_name '];
echo $row[' student_rollno '];
echo $row[' student_course '];
}

$pagecount = 50; // Total number of rows


$num = $pagecount / $page_result ;

if($_GET['pageno'] > 1)
{
echo "<a href = 'samepage.php?pageno = ".($_GET['pageno'] - 1)." '> Prev </a>";
}
for($i = 1 ; $i <= $num ; $i++)
{
echo "<a href = "samepage.php?pageno = ". $i ." >". $i ."</a>";
}
if($num! = 1)
{
echo "<a href = 'samepage.php?pageno = ".($_GET['pageno'] + 1)." '> Next </a>";
}

?>

In this step we get the results from student_info table, in student_info table we
have three columns student_name, student_rollno, student_course.

Then, we use $pagecount = 50 because there are 50 rows in student_info table.


Then, we use $num variable and set the value returned by $pagecount /
$page_result.

The first if statement display the Prev page link if the pageno is greater than 1
and then we display all the pagination links using for loop upto the $num value.

The second if statement display the Next page link if the pageno is not equal to
1. Remember always do proper form validation before and after submitting the
form.

That's all, this is how to create and implete the basic PHP Pagination with
MySQL. You can customize this code further as per your requirement. And
please feel free to give comments on this tutorial.

And if you like this tutorials please share it with your friends via Email or Social
Media.

imple PHP Jquery Ajax


CRUD(insert update delete) tutorial
example with source code
Today, I want to share with you PHP Mysql CRUD using Jquery Ajax from
scratch. CRUD stands for Create, Read, Update and Delete database data. Add,
Edit, Update, and Delete functionality is used almost every PHP application. But
today i will show you very simple way to crud using bootstrap model.
In this tutorial we will do insert, update and delete task for items. In this example i
also use bootstrap for layout. I write just few step to follow you can make simple
crud application with jquery pagination in your laravel 5 project.
In this example i used several jquery Plugin for fire Ajax, Ajax pagination,
Bootstrap, Bootstrap Validation, notification as listed bellow.
1.Jquery
2.Bootstrap
3.twbsPagination js
4.Validator JS(Bootstrap form validation example with demo using validator.js
plugin)
5.toastr JS(Jquery notification popup box example using toastr JS plugin with
demo)
this simple ajax crud example, i created "Item Management" with you can do
several option like as bellow:
1. Item Listing
2. Item Create
3. Item Edit
4. Item Delete
you can implement crud application from scratch, so no worry if you can
implement through bellow simple step. After create successful example, you will
find layout as bellow:
Preview:
Step 1: Create items table and DB Config file
In first step we should create database and items table. so let's create database i
did create "h_blog" database and "items" table inside that database. so you can
create database as you want but you have to create "items" table if you are doing
from scratch. so create "items" table using following mysql query:
Items Table Query:

CREATE TABLE IF NOT EXISTS `items` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,


`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

`description` text COLLATE utf8_unicode_ci NOT NULL,

`created_at` timestamp NULL DEFAULT NULL,

`updated_at` timestamp NULL DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci


AUTO_INCREMENT=63 ;

Ok, let's proceed this way, we are doing from scratch so we require to create
database configration file that way we can use that file in many other file. so let's
create api directory and create db_config.php file in api directory and put bellow
code:
api/db_config.php

<?php

define (DB_USER, "root");

define (DB_PASSWORD, "root");

define (DB_DATABASE, "h_blog");

define (DB_HOST, "localhost");

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD,


DB_DATABASE);

?>

In Above file please make sure to check your batabase configuration because
could problem you find somewhere. that's way i tell you check it two times. It was
just for your kind information.
Step 2: Create index.php File
Ok, now we also require to create index.php file in our root directory. In this file i
added "url" variable in js for site root URL. You can update also with your site
URL. so let's create index.php file and put bellow content in that file.
index.php

<!DOCTYPE html>

<html>

<head>

<title>PHP Jquery Ajax CRUD Example</title>

<link rel="stylesheet" type="text/css"


href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstr
ap.min.css">

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.j
s"></script>

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/twitter-
bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/twbs-
pagination/1.3.1/jquery.twbsPagination.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-
bootstrap-validator/0.11.5/validator.min.js"></script>

<script type="text/javascript"
src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.
min.js"></script>

<link
href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toast
r.min.css" rel="stylesheet">

<script type="text/javascript">

var url = "http://localhost:8000/";


</script>

<script src="/js/item-ajax.js"></script>

</head>

<body>

<div class="container">

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>PHP Jquery Ajax CRUD Example</h2>

</div>

<div class="pull-right">

<button type="button" class="btn btn-


success" data-toggle="modal" data-target="#create-item">

Create Item

</button>

</div>

</div>

</div>

<table class="table table-bordered">

<thead>
<tr>

<th>Title</th>

<th>Description</th>

<th width="200px">Action</th>

</tr>

</thead>

<tbody>

</tbody>

</table>

<ul id="pagination" class="pagination-sm"></ul>

<!-- Create Item Modal -->

<div class="modal fade" id="create-item" tabindex="-


1" role="dialog" aria-labelledby="myModalLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close" data-


dismiss="modal" aria-label="Close"><span aria-
hidden="true">×</span></button>

<h4 class="modal-title"
id="myModalLabel">Create Item</h4>

</div>
<div class="modal-body">

<form data-toggle="validator"
action="api/create.php" method="POST">

<div class="form-group">

<label
class="control-label" for="title">Title:</label>

<input type="text"
name="title" class="form-control" data-error="Please enter
title." required />

<div class="help-
block with-errors"></div>

</div>

<div class="form-group">

<label
class="control-label" for="title">Description:</label>

<textarea
name="description" class="form-control" data-error="Please enter
description." required></textarea>

<div class="help-
block with-errors"></div>

</div>

<div class="form-group">
<button
type="submit" class="btn crud-submit btn-success">Submit</button>

</div>

</form>

</div>

</div>

</div>

</div>

<!-- Edit Item Modal -->

<div class="modal fade" id="edit-item" tabindex="-1"


role="dialog" aria-labelledby="myModalLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close" data-


dismiss="modal" aria-label="Close"><span aria-
hidden="true">×</span></button>

<h4 class="modal-title"
id="myModalLabel">Edit Item</h4>

</div>
<div class="modal-body">

<form data-toggle="validator"
action="api/update.php" method="put">

<input type="hidden" name="id"


class="edit-id">

<div class="form-group">

<label
class="control-label" for="title">Title:</label>

<input type="text"
name="title" class="form-control" data-error="Please enter
title." required />

<div class="help-
block with-errors"></div>

</div>

<div class="form-group">

<label
class="control-label" for="title">Description:</label>

<textarea
name="description" class="form-control" data-error="Please enter
description." required></textarea>

<div class="help-
block with-errors"></div>

</div>
<div class="form-group">

<button
type="submit" class="btn btn-success crud-submit-
edit">Submit</button>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

</body>

</html>

Step 3: Create JS File


In this step we will create jquery file and write ajax request code on it. So first
create js folder on your root directory and then create item-ajax.js file on it.
js/item-ajax.js

$( document ).ready(function() {

var page = 1;

var current_page = 1;
var total_page = 0;

var is_ajax_fire = 0;

manageData();

/* manage data list */

function manageData() {

$.ajax({

dataType: 'json',

url: url+'api/getData.php',

data: {page:page}

}).done(function(data){

total_page = Math.ceil(data.total/10);

current_page = page;

$('#pagination').twbsPagination({

totalPages: total_page,

visiblePages: current_page,

onPageClick: function (event, pageL) {

page = pageL;

if(is_ajax_fire != 0){

getPageData();
}

});

manageRow(data.data);

is_ajax_fire = 1;

});

/* Get Page Data*/

function getPageData() {

$.ajax({

dataType: 'json',

url: url+'api/getData.php',

data: {page:page}

}).done(function(data){

manageRow(data.data);

});

}
/* Add new Item table row */

function manageRow(data) {

var rows = '';

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

rows = rows + '<tr>';

rows = rows + '<td>'+value.title+'</td>';

rows = rows + '<td>'+value.description+'</td>';

rows = rows + '<td data-id="'+value.id+'">';

rows = rows + '<button data-toggle="modal" data-


target="#edit-item" class="btn btn-primary edit-
item">Edit</button> ';

rows = rows + '<button class="btn btn-danger remove-


item">Delete</button>';

rows = rows + '</td>';

rows = rows + '</tr>';

});

$("tbody").html(rows);

/* Create new Item */

$(".crud-submit").click(function(e){

e.preventDefault();
var form_action = $("#create-
item").find("form").attr("action");

var title = $("#create-


item").find("input[name='title']").val();

var description = $("#create-


item").find("textarea[name='description']").val();

if(title != '' && description != ''){

$.ajax({

dataType: 'json',

type:'POST',

url: url + form_action,

data:{title:title, description:description}

}).done(function(data){

$("#create-
item").find("input[name='title']").val('');

$("#create-
item").find("textarea[name='description']").val('');

getPageData();

$(".modal").modal('hide');

toastr.success('Item Created Successfully.', 'Success


Alert', {timeOut: 5000});

});

}else{

alert('You are missing title or description.')


}

});

/* Remove Item */

$("body").on("click",".remove-item",function(){

var id = $(this).parent("td").data('id');

var c_obj = $(this).parents("tr");

$.ajax({

dataType: 'json',

type:'POST',

url: url + 'api/delete.php',

data:{id:id}

}).done(function(data){

c_obj.remove();

toastr.success('Item Deleted Successfully.', 'Success


Alert', {timeOut: 5000});

getPageData();

});

});
/* Edit Item */

$("body").on("click",".edit-item",function(){

var id = $(this).parent("td").data('id');

var title =
$(this).parent("td").prev("td").prev("td").text();

var description = $(this).parent("td").prev("td").text();

$("#edit-item").find("input[name='title']").val(title);

$("#edit-
item").find("textarea[name='description']").val(description);

$("#edit-item").find(".edit-id").val(id);

});

/* Updated new Item */

$(".crud-submit-edit").click(function(e){

e.preventDefault();

var form_action = $("#edit-


item").find("form").attr("action");

var title = $("#edit-


item").find("input[name='title']").val();
var description = $("#edit-
item").find("textarea[name='description']").val();

var id = $("#edit-item").find(".edit-id").val();

if(title != '' && description != ''){

$.ajax({

dataType: 'json',

type:'POST',

url: url + form_action,

data:{title:title, description:description,id:id}

}).done(function(data){

getPageData();

$(".modal").modal('hide');

toastr.success('Item Updated Successfully.', 'Success


Alert', {timeOut: 5000});

});

}else{

alert('You are missing title or description.')

});

});

Step 4: Create API File


In this step we require to create api file for getting item Data, Add item Data,
update item Data and delete item Data. So let's create api file one by one.
api/getData.php

<?php

require 'db_config.php';

$num_rec_per_page = 5;

if (isset($_GET["page"])) { $page = $_GET["page"]; } else {


$page=1; };

$start_from = ($page-1) * $num_rec_per_page;

$sqlTotal = "SELECT * FROM items";

$sql = "SELECT * FROM items Order By id desc LIMIT $start_from,


$num_rec_per_page";

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

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

$json[] = $row;

}
$data['data'] = $json;

$result = mysqli_query($mysqli,$sqlTotal);

$data['total'] = mysqli_num_rows($result);

echo json_encode($data);

?>

api/create.php

<?php

require 'db_config.php';

$post = $_POST;

$sql = "INSERT INTO items (title,description)

VALUES ('".$post['title']."','".$post['description']."')";

$result = $mysqli->query($sql);
$sql = "SELECT * FROM items Order by id desc LIMIT 1";

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

$data = $result->fetch_assoc();

echo json_encode($data);

?>

api/update.php

<?php

require 'db_config.php';

$id = $_POST["id"];

$post = $_POST;

$sql = "UPDATE items SET title = '".$post['title']."'

,description = '".$post['description']."'

WHERE id = '".$id."'";
$result = $mysqli->query($sql);

$sql = "SELECT * FROM items WHERE id = '".$id."'";

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

$data = $result->fetch_assoc();

echo json_encode($data);

?>

api/delete.php

<?php

require 'db_config.php';

$id = $_POST["id"];

$sql = "DELETE FROM items WHERE id = '".$id."'";

$result = $mysqli->query($sql);
echo json_encode([$id]);

?>

Step 5: Run Example


Ok now we are ready to run this example by following command:

php -S localhost:8000

Check on Browser URL like as bellow:

http://localhost:8000

I hope it can help you...

Star Rating System Using PHP


and JavaScript.
To create a Star Rating System it takes only Four steps:-
1. Create a database Table to store the Ratings
2. Make a PHP file and define markup and script for Star Rating System
3. Make a PHP file to store the ratings for Star Rating System
4. Make a CSS file and define styling for Star Rating System

Step 1.Create a database Table to store the Ratings


We have to create a database table named rating having four columns
id,php,asp,jsp
CREATE TABLE `rating` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`php` int(11) NOT NULL,
`asp` int(11) NOT NULL,
`jsp` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

Step 2.Make a PHP file and define markup and script for Star Rating System
We make a PHP file and save it with a name ratings.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="rating_style.css">
<script type="text/javascript">

function change(id)
{
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;

for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
}

</script>

</head>

<body>
<h1>Star Rating System Using PHP and JavaScript</h1>

<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";

$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$select_rating=mysql_query("select php,asp,jsp from rating");


$total=mysql_num_rows($select_rating);

while($row=mysql_fetch_array($select_rating))
{
$phpar[]=$php;
$aspar[]=$asp;
$jspar[]=$jsp;

}
$total_php_rating=(array_sum($phpar)/$total);
$total_asp_rating=(array_sum($aspar)/$total);
$total_jsp_rating=(array_sum($jspar)/$total);

?>

<form method="post" action="insert_rating.php">


<p id="total_votes">Total Votes:<?php echo $total;?></p>
<div class="div">
<p>PHP (<?php echo $total_php_rating;?>)</p>
<input type="hidden" id="php1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="php1"
class="php">
<input type="hidden" id="php2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="php2"
class="php">
<input type="hidden" id="php3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="php3"
class="php">
<input type="hidden" id="php4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="php4"
class="php">
<input type="hidden" id="php5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="php5"
class="php">
</div>

<div class="div">
<p>ASP (<?php echo $total_asp_rating;?>)</p>
<input type="hidden" id="asp1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp1"
class="asp">
<input type="hidden" id="asp2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp2"
class="asp">
<input type="hidden" id="asp3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp3"
class="asp">
<input type="hidden" id="asp4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp4"
class="asp">
<input type="hidden" id="asp5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp5"
class="asp">
</div>

<div class="div">
<p>JSP (<?php echo $total_jsp_rating;?>)</p>
<input type="hidden" id="jsp1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp1"
class="jsp">
<input type="hidden" id="jsp2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp2"
class="jsp">
<input type="hidden" id="jsp3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp3"
class="jsp">
<input type="hidden" id="jsp4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp4"
class="jsp">
<input type="hidden" id="jsp5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp5"
class="jsp">
</div>

<input type="hidden" name="phprating" id="phprating" value="0">


<input type="hidden" name="asprating" id="asprating" value="0">
<input type="hidden" name="jsprating" id="jsprating" value="0">
<input type="submit" value="Submit" name="submit_rating">

</form>

</body>
</html>
In this step we made 3 div element to rate three programming language
PHP,ASP,JSP and put the star image in them whenever the user wants to give
ratings user has to put the mouse over the star and we call a change function
which get the star id and change the star image to coloured means.You may also
like live voting system using Ajax and PHP.

In javascript change(id) function we get the id of star which the user put the
mouse over that and then we make 2 for loops one is to blink all the previous star
including him and second one is to blank all the next star excluding him.

And after that we use connect to the database and get Total votes and there
rating by getting total ratings per language and then divide then divide each
rating with total votes.You can also view our create captcha system using
PHP tutorial to add captcha on rating system.

Step 3.Make a PHP file to store the ratings for Star Rating System
We make a PHP file named insert_rating.php
<?php
if(isset($_POST['submit_rating']))
{
$host="localhost";
$username="root";
$password="";
$databasename="sample";

$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$php_rating=$_POST['phprating'];
$asp_rating=$_POST['asprating'];
$jsp_rating=$_POST['jsprating'];
$insert=mysql_query("insert into rating
values('','$php_rating','$asp_rating','jsp_rating')");
}
?>

In this step we get the value and store them to database.You can do validation to
make your code more secure or you can view our How to do validation before
and after submitting the form tutorial.

Step 4.Make a CSS file and define styling for Star Rating System
We make a CSS file and save it with name rating_style.css.
body
{
background-color:#0B4C5F;
font-family:helvetica;
text-align:center;
}
h1
{
margin-top:20px;
font-size:40px;
color:#E6E6E6;
}
#total_votes
{
font-size:30px;
color:#FE2E2E;
font-weight:bold;
}
.div
{
border:1px solid #E6E6E6;
clear:both;
margin-top:20px;
height:100px;
width:400px;
padding:10px;
margin-left:300px;
border-radius:3px;
}
.div p
{
margin:0px;
font-size:20px;
text-align:left;
color:#E6E6E6;
}
img
{
margin-top:10px;
width:50px;
height:50px;
float:left;

}
input[type="submit"]
{
border:none;
background:none;
background-color:#585858;
width:100px;
height:50px;
color:white;
border-radius:3px;
font-size:17px;
margin-top:20px;
}

Thats all, this is how to create a Star Rating System Using PHP and
JavaScript.You can customize this code further as per your requirement. And
please feel free to give comments on this tutorial.

Sticky Social Icons in Sidebar using


jQuery

Sharing webpage to the social media is used to gain enormous reach for our
webpage. So adding social icons to the webpage is very important to let the
readers share your article. Readers want to share the website at any moment
while they are reading your page. So, it would be better to give high visibility
for the social share icons of your page.
In this tutorial, we create sticky social share icons in the sidebar to be visible at
any moment while scrolling. We use jQuery to get the CSS properties of the
social share icon element and manipulating its position on page scroll. On the
page scroll, the code will compare the position of the window and the social
icon element. Based on the comparison, it will change the social icons position
to make it sticky. In a previous tutorial, we have seen how to create floating
contact form on page scroll using jQuery.

view demo

HTML for Sticky Social Icons in Sidebar

The following code shows the HTML for the webpage with the sticky social
icons in the sidebar. The social icons in the left sidebar are displayed after the
list of menu items.
<div>

<div class="left-side-bar">

<ul>

<li>Integer Vitae</li>

<li>Vivamus Lacinia</li>

<li>Donec Rutrum</li>

<li>Sed Lacinia</li>

<li>Morbi ut Turpis</li>

<li>Rhoncus Nunc</li>

<li>Sed id Turpis</li>

<li>Vestibulum Commodo</li>

<li>Pellentesque Nec</li>

<li>Fusce Amet</li>

<li>Donec Sem</li>

<li>Praesent Iaculis</li>

<li>Tellus Tincidunt</li>

<li>Nunc Mollis</li>

<li>Quisque Urna</li>

</ul>

<div class="social-icon">

<img src="icon/facebook-social.png"

title="Share on Facebook" /> <img


src="icon/twitter-social.png" title="Share on
Twitter" />

<img src="icon/linkedin-social.png"

title="Share on Linkedin" /> <img

src="icon/email-social.png" title="Share on
Email" />

</div>

</div>

<div class="main-content">

<p>Quisque vitae erat et turpis sollicitudin sodales.


Morbi

auctor placerat urna at sodales. Class aptent


taciti

sociosqu ad litora torquent per conubia nostra, per


inceptos

himenaeos. Nunc faucibus arcu sit amet nibh


convallis

blandit. Nullam et sapien ac eros aliquam eleifend


a sed

odio. Proin in ex imperdiet augue suscipit maximus.

Pellentesque malesuada, diam a mollis varius, felis


sapien

pharetra felis, a suscipit leo massa sit amet


magna. Morbi

maximus lacus a ex varius semper. Aliquam erat


volutpat. Sed
luctus turpis sollicitudin facilisis cursus.
Vestibulum

sodales ligula eu congue placerat. Curabitur est


orci,

suscipit vel blandit sed, commodo at sem. Duis id


facilisis

augue, vel ornare est. Aenean sollicitudin, odio in


ultrices

faucibus, neque quam facilisis nunc, eu bibendum


eros quam

eu dolor.</p>

</div>

</div>

And the styles are

<style>

body {

font-family: Arial;

.left-side-bar {

width: 250px;

float: left;

}
.main-content {

float: left;

width: 80%;

height:100px;

font-size: 1.2em;

line-height: 70px;

color: #919c9e;

.left-side-bar ul li {

padding: 15PX;

background: #bdcacc;

margin: 0px;

COLOR: #5c6567;

border-bottom: #c9d6d8 1px solid;

.left-side-bar ul {

list-style: none;

margin: 0px 20px 0px 0px;

padding: 0PX;

}
.social-icon {

padding: 20px;

.social-icon img {

padding: 0px 5px;

</style>

jQuery on Scroll Sticky Social Icons

The following jQuery code is used to make the social share icons in the
sidebar to be sticky. The code gets the window scroll top and the Social icons
top position and compares them on page scroll event. When the top of the
scrolling window exceeds than that of the social icons, the code manipulates
the social icons element top position to make it sticky.

<script>

$(document).ready(function(){

$( window ).scroll(function() {

$( ".social-icon" ).css("position",
"relative");

$( ".social-icon" ).css("top", 0);

if($( window ).scrollTop() > $( ".social-icon"


).position().top) {
$( ".social-icon" ).css("position",
"absolute");

$( ".social-icon" ).css("top", $( window


).scrollTop());

});

});

</script>

Sticky Social Icons in Sidebar – Output

The following screenshot shows the web page output with the sticky social
share icons in the sidebar.

TWITTER LIKE COUNT REMAINING


CHARACTER USING JQUERY
Twitter has a nice feature in which it will show how many characters remaining of your
tweet. It also limits the characters to only 160. In this post i will show you how to do
twitter like count remaining character using Jquery.

Live Demo
It is very interesting and easy to code. Use it to enrich your web application.
The Html
This is our html file. Simple enough, just using textarea, button and a span to
dynamically change the number of remaining characters.
1
<body>
2 <div id="box">
3 <p>(Maximum Allowed Characters : 160)</p>
4 <p><textarea id="area" rows="10" cols="40"></textarea></p>
5 <span id="message"> 160 </span> Characters Remaining
6 <input type="button" id="tweet" value="Tweet"/>
</div>
7 <body>
8
The Java Script
On the first load page of our count remaining character using jquery, we set the button
to be disabled and also when the characters is greater than 160 or equal or less than 0.
There are two other methods that are invoked when characters are greater than 160 or
equal or less than 0, it is a method to make the text inside textarea become line through
and a method to make the number of remaining characters become red.
1
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
2 <script type="text/javascript">
3 $(document).ready(function(){
4 $("#tweet").attr("disabled","disabled");
5 $("#area").keyup(function(){
var chars=$(this).val().length;
6
7 $("#message").text(160-chars);
8
9 if(chars > 160 || chars <=0){
10 $("#tweet").attr("disabled","disabled");
11 $("#message").addClass("minus");
12 $(this).css("text-decoration","line-through");
13
}else{
14 $("#tweet").removeAttr("disabled");
15 $("#message").removeClass("minus");
16 $(this).css("text-decoration","");
17 }
18 });
});
19 </script>
20
21
22
The CSS
This Css make our web application looks beautiful, not only a white page. .minus class
is added and removed dynamically when application is running. It depends on
remaining characters, whether remaining characters are greater than 160 or equal to or
less than zero like i said above.
1
2
3 <style type="text/css">
#box{
4
width:400px;
5 height:230px;
6 background-color: pink;
7 margin:50 auto 0;
8 padding-top:20px;
padding-left:40px ;
9 }
10
11 p{
12 margin: 0;
13 }
14
15 #area{
margin-bottom: 10px;
16 }
17
18 #tweet{
19 margin-left: 130px;
20 }
21
.minus{
22 color: red;
23 }
24 </style>
25
26
Here’s some screenshot of our web app
Upload multiple images using jQuery, Ajax and
PHP

We’ve received many requests from followers for publishing the tutorial on How to upload
multiple images without refreshing the page. We’ll try to simplify the multiple images upload
without refreshing the page. In this simple tutorial, we’ll discuss multiple images uploads using
jQuery, Ajax and PHP. Using our script, you can upload multiple images at once without page
refresh using jQuery, Ajax and PHP.

We’ll show you two ways to display images after upload. Once the images are uploaded to the
server via jQuery, you can display images without stored in a folder or stored in a folder. This
script is very short, easy and useful which can easily be implemented in your web projects.

Read the following step-by-step guide to understanding the whole process of Upload multiple
images using jQuery, Ajax and PHP. Also, you can see the live demo from the Demo link and
download the source code from the Download link at the end of the tutorial.
index.html File

index.html file contains some JavaScript and HTML codes. All codes are given below.

JavaScript Code:
At first include the two external JavaScript library
files, jquery.min.js and jquery.form.js . jquery.min.js is the main jQuery library and
another jquery.form.js file is used to submit the form with files for uploading using jQuery
Ajax.

<script type="text/javascript" src="jquery.min.js"></script>


<script type="text/javascript" src="jquery.form.js"></script>

Now write some JavaScript code for form submission and displaying the uploaded images.

<script type="text/javascript">
$(document).ready(function(){
$('#images').on('change',function(){
$('#multiple_upload_form').ajaxForm({
//display the uploaded images
target:'#images_preview',
beforeSubmit:function(e){
$('.uploading').show();
},
success:function(e){
$('.uploading').hide();
},
error:function(e){
}
}).submit();
});
});
</script>

HTML Code

Input file field name is defined as an array for accept multiple file name and also used multiple
attributes for multiple upload support.

<form method="post" name="multiple_upload_form" id="multiple_upload_form"


enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label>&nbsp;</label>
<img src="uploading.gif" alt="uploading......"/>
</div>
</form>

Create div with target id which is defined at the above JavaScript code. The uploaded images
would be displayed at this div. Also you can change this div id, but remember that the JavaScript
target option value ( target:'#images_preview' ) will be same with this div id.
<div id="images_preview"></div>

upload.php file:

upload.php file contain some PHP codes for process the uploading and generates the images

view. There are two way to upload images and display the images.

One Way is to create a folder named uploads/ . Upload the images and stored in the folder.

<?php
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
//upload and stored images
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
}
}
?>

You can upload the images and display the images without stored in the folder.

<?php
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
//display images without stored
$extra_info = getimagesize($_FILES['images']['tmp_name'][$key]);
$images_arr[] = "data:" . $extra_info["mime"] . ";base64," . base64_encod
e(file_get_contents($_FILES['images']['tmp_name'][$key]));
}
?>

Generate images view


After uploading the images we need to generate the view. This view will display at the target div.

<?php
if(!empty($images_arr)){
foreach($images_arr as $image_src){ ?>
<ul>
<li >
<img src="<?php echo $image_src; ?>" alt="">
</li>
</ul>
<?php }
}
?>

Conclusion

This tutorial and script helps to upload multiple images using jQuery Ajax and PHP. If you’re
looking the advanced uploading feature in your web project, you can implement Drag and drop
file upload using Dropzone JS and PHP. Otherwise, for simple image upload, you can Upload an
image and create thumbnail using PHP.

Validate The Form Data Before


And After Submitting The Form
Using JavaScript And PHP.
You can validate form data before and after submitting the form in just two simple
steps:-
1. Make a HTML form and do Client-Side validation
2. Recieve the form data and do Server-Side validation

Step 1.Make a HTML form and do Client-Side validation


We make a HTML form with post method and save it with a
name validated_form.html
<html>
<head>

<script type="text/javascript">
function validate()
{
var error="";
var name = document.getElementById( "name_of_user" );
if( name.value == "" )
{
error = " You Have To Write Your Name. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}

var email = document.getElementById( "email_of_user" );


if( email.value == "" || email.value.indexOf( "@" ) == -1 )
{
error = " You Have To Write Valid Email Address. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}

var password = document.getElementById( "password_of_user" );


if( password.value == "" || password.value >= 8 )
{
error = " Password Must Be More Than Or Equal To 8 Digits. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}

else
{
return true;
}
}

</script>
</head>
<body>

<form method="POST" action="getdata.php" onsubmit="return validate();">


<input type="text" name="username" id="name_of_user">
<input type="text" name="useremail" id="email_of_user">
<input type="password" name="user_password" id="password_of_user">
<input type="submit" name="submit_form" value="Submit">
</form>

<p id="error_para" ></p>

</body>
</html>

You can do more validation on Client-Side as per your need to make your code
more secure.We submit the data from this HTML form to getdata.php where we
do Server-Side validation and then insert out data in database.You may also
like validate email and password using jQuery.

Step 2.Recieve the form data and do Server-Side validation


In this step we get all the data which get get from validated_form.html page and
put Server-Side validation using PHP and then we insert all the secure data into
the database.
// getdata.php

<?php
if( isset( $_POST['submit_form'] ) )
{
validate_data($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
$data = mysqli_real_escape_string($data);
return $data;
}

$name = validate_data( $_POST['username'] );


$emailid = validate_data( $_POST['useremail'] );
$password = validate_data( $_POST['user_password'] );

$host = 'localhost';
$user = 'root';
$pass = ' ';

mysql_connect($host, $user, $pass);


mysql_select_db('demo');

$insertdata=" INSERT INTO user_data VALUES( '$name','$emailid','$password' ) ";


mysqli_query($insertdata);
}
?>

You can do more validation on Server-Side as per your need to make your code
more secure.Use only MySQLi or PDO where possible because they are more
secure than MySQL.

You can also add google recaptcha in form to make your form more secure and
prevent from spamming.That's all, this is how to validate the form data before
and after submitting the form using JavaScript and PHP. You can customize this
code further as per your requirement. And please feel free to give comments on
this tutorial.

Potrebbero piacerti anche