(Kumpulan Tutorial) Bootstrap, PHP-MySQL, Jquery
(Kumpulan Tutorial) Bootstrap, PHP-MySQL, Jquery
(Kumpulan Tutorial) Bootstrap, PHP-MySQL, Jquery
Live Demo
Download Script
Database Design/Table
this is our database design with members table containing some dumping data, this will be
shown in bootstrap modal dynamically.
--- Database: `dbtest`
--
Connect to Database
this is database connection file queried with PDO extensiion so copy the following code and
create a new file as dbconfig.php then paste the copied below code inside the file.
<?php
$DBhost
$DBuser
$DBpass
$DBname
=
=
=
=
"localhost";
"root";
"";
"dbtest";
try {
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex){
die($ex->getMessage());
}
<thead>
<tr>
<th>Full Name</th>
<th>View Profile</th>
</tr>
</thead>
<tbody>
<?php
require_once 'dbconfig.php';
$query = "SELECT * FROM tbl_members";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $row['first_name']." ".$row['last_name']; ?
></td>
<td>
<button data-toggle="modal" data-target="#view-modal" data-id="<?
php echo $row['user_id']; ?>" id="getUser" class="btn btn-sm btn-info"><i
class="glyphicon glyphicon-eye-open"></i> View</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
as you can see every row has a view button and when any of button will get clicked a popup
modal will be displayed with particular clicked row with full row detail in bootstrap modal
dynamically.
button has a id="getUser" attribute and whenever it get clicked a popup modal will be
appeared with mysql data of that particular id(row).
require_once 'dbconfig.php';
if (isset($_REQUEST['id'])) {
$id = intval($_REQUEST['id']);
$query = "SELECT * FROM tbl_members WHERE user_id=:id";
$stmt = $DBcon->prepare( $query );
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
?>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>First Name</th>
<td><?php echo $first_name; ?></td>
</tr>
<tr>
<th>Last Name</th>
<td><?php echo $last_name; ?></td>
</tr>
<tr>
<th>Email ID</th>
<td><?php echo $email; ?></td>
</tr>
<tr>
<th>Position</th>
<td><?php echo $position; ?></td>
</tr>
<tr>
<th>Office</th>
<td><?php echo $office; ?></td>
</tr>
</table>
</div>
<?php
ok, we have just seen ajax request with html datatype now we will see ajax request with
json datatype, let's fill modal with json data.
-->
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>First Name</th>
<td id="txt_fname"></td>
</tr>
<tr>
<th>Last Name</th>
<td id="txt_lname"></td>
</tr>
<tr>
<th>Email ID</th>
<td id="txt_email"></td>
</tr>
<tr>
<th>Position</th>
<td id="txt_position"></td>
</tr>
<tr>
<th>Office</th>
<td id="txt_office"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" datadismiss="modal">Close</button>
</div>
</div>
</div>
</div>
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
exit;
}
Ok, We have just covered here simple yet useful script about showing data from mysql
dynamically in bootstrap modal with the help of ajax, both response datatypes, hope you guys
like this tutorial, and please don't forget to share it, if you like it then just share it, and feel
free to ask any queries about any of tutorial.
That's it.
Live Demo
Download Script
for this tutorial i have created here a simple HTML form which will take some inputs from
the user , first name, last name, email id and contact no, below form is in div tag which have
id and class attributes to perform jQuery effects.
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname"
placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact"
id="lname" placeholder="Contact No" required />
</div>
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
Files we need
guys i have used bootstrap for the design so add the following style sheet and javascript files.
Add Bootstrap CSS file
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
});
});
submit.php
as i said data will be posted via submit.php file, so here is the file with simple mixed php
and html code and displayed within index file without page refresh, it will accepts data via
$.ajax() call and display the results in "index.php" file.
<?php
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
?>
<table class="table table-striped" border="0">
<tr>
<td colspan="2">
<div class="alert alert-info">
<strong>Success</strong>, Form Submitted Successfully...
</div>
</td>
</tr>
<tr>
<td>First Name</td>
<td><?php echo $fname ?></td>
</tr>
<tr>
<td>Last Name</td>
<td><?php echo $lname ?></td>
</tr>
<tr>
<td>Your eMail</td>
<td><?php echo $email; ?></td>
</tr>
<tr>
<td>Contact No</td>
<td><?php echo $phno; ?></td>
</tr>
</table>
<?php
}
});
$.post('submit.php', $(this).serialize() )
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
that's it, here how you can easily submit forms using jQuery without Page Refresh, well this
is just for beginners to show how forms data can be pass through the jQuery, we will see
complete crud tutorial on jQuery CRUD very soon, hope you like it.
Live Demo
Download Script
Note : Bootbox.js
Bootbox.js is a small JavaScript library which allows you to create programmatic dialog
boxes using Bootstrap modals, without having to worry about creating, managing or
removing any of the required DOM elements or JS event handlers.
Note taken from the official site.
-- Database: `dbtest`
--- ---------------------------------------------------------- Table structure for table `tbl_products`
-CREATE TABLE IF NOT EXISTS `tbl_products` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(35) NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--- Dumping data for table `tbl_products`
-INSERT INTO `tbl_products` (`product_id`, `product_name`) VALUES
(1, 'Galaxy Jmax'),
(2, 'Killer Note5'),
(3, 'Asus ZenFone2'),
(4, 'Moto Xplay'),
(5, 'Lenovo Vibe k5 Plus'),
(6, 'Redme Note 3'),
(7, 'LeEco Le 2'),
(8, 'Apple iPhone 6S Plus');
Database Configuration
Common and Simple Database configuration/connection code with PDO extension, edit the
following file as per your database credentials and save it as "dbconfig.php"
<?php
$DBhost
$DBuser
$DBpass
$DBname
=
=
=
=
"localhost";
"root";
"";
"dbtest";
try{
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
Attribute data-id which stores product id and this will trigger out by delete_product
class using jQuery's click event, using this we can get the product id to get deleted from table.
<table class="table table-bordered table-condensed table-hover tablestriped">
<tr>
<th>#ID</th>
<th>Product Name</th>
<th>Action</th>
</tr>
<?php
require_once 'dbconfig.php';
$query = "SELECT product_id, product_name FROM tbl_products";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_ASSOC) ) {
extract($row);
?>
<tr>
<td><?php echo $product_id; ?></td>
<td><?php echo $product_name; ?></td>
<td>
<a class="delete_product" data-id="<?php echo
$product_id; ?>" href="javascript:void(0)">
<i class="glyphicon glyphicon-trash"></i>
</a></td>
</tr>
<?php
}
?>
</table>
following is the simple confirm dialog code, but i have used here bootbox custom dialog.
Confirm Dialog
bootbox.confirm("Are you sure?", function(result) {
// delete code here
});
Custom Dialog
this is a custom dialog i have used here to do some ajax callback's mainly to delete the data
using ajax method. in the delete button function i have make an ajax call to delete the current
clicked row.
bootbox.dialog({
message: "I am a custom dialog",
title: "Custom title",
buttons: {
success: {
label: "No!",
className: "btn-success",
callback: function() {
// cancel button, close dialog box
}
}
});
},
danger: {
label: "Delete!",
className: "btn-danger",
callback: function() {
// jquery ajax delete code here
}
}
$.post('delete.php', { 'delete':pid })
.done(function(response){
bootbox.alert(response);
parent.fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
delete.php
this file will called silently via ajax and after getting the id of specific clicked row it will
delete the row and displays the product deletion message in alert box as a response.
<?php
require_once 'dbconfig.php';
if ($_REQUEST['delete']) {
$pid = $_REQUEST['delete'];
$query = "DELETE FROM tbl_products WHERE product_id=:pid";
$stmt = $DBcon->prepare( $query );
$stmt->execute(array(':pid'=>$pid));
if ($stmt) {
echo "Product Deleted Successfully ...";
}
}
$.ajax({
type: 'POST',
url: 'delete.php',
data: 'delete='+pid
})
.done(function(response){
bootbox.alert(response);
parent.fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
});
});
</script>
How it goes :
$('.delete_product').click() : product deleting click event.
var pid = $(this).attr('data-id'); : get product id.
var parent = $(this).parent("td").parent("tr"); : get the clicked <tr>
row to fade out.
Hope you guy's like this tutorial, and please don't forget to share this tutorial with you
friends. if you are using bootstrap for your projects then you must use this, so download the
code and try...
Download Script
Database / Table
"testdb" named database is used in this tutorial, so create it and paste the following sql code
in your phpmyadmin it will create users table "tbl_users".
CREATE TABLE IF NOT EXISTS `tbl_users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(20) NOT NULL,
`userProfession` varchar(50) NOT NULL,
`userPic` varchar(200) NOT NULL,
PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;
now we have to create only 4 files php files which will handle our crud operations with an
image and they are as follow.
dbconfig.php
simple host/database configuration file created with PDO Query/Extension. change the
credentials as per your configuration.
<?php
$DB_HOST
$DB_USER
$DB_PASS
$DB_NAME
=
=
=
=
'localhost';
'root';
'';
'testdb';
try{
$DB_con = new PDO("mysql:host={$DB_HOST};dbname={$DB_NAME}",$DB_USER,
$DB_PASS);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
addnew.php
Simple HTML form created with bootstrap, the fields i have taken here for user is username,
userjob, and userimage, you can also add more fields.
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label">Username.</label></td>
<td><input class="form-control" type="text" name="user_name"
placeholder="Enter Username" value="<?php echo $username; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Profession(Job).</label></td>
<td><input class="form-control" type="text" name="user_job"
placeholder="Your Profession" value="<?php echo $userjob; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Profile Img.</label></td>
<td><input class="input-group" type="file" name="user_image"
accept="image/*" /></td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="btnsave" class="btn
btn-default">
<span class="glyphicon glyphicon-save"></span> save
</button>
</td>
</tr>
</table>
</form>
as i told that, i have used her bootstrap for this tutorial so actual file code looks lengthy, that's
why i have putted here only important and main code, the designing code is avoided. now let
come to the next point.
PHP Code :
put the following php code just above starting <!DOCTYPE html> tag. in this script an image
and user details will be inserted, proper image validation is there or if any error occured an
appropriate message will be displayed with bootstrap design.
<?php
error_reporting( ~E_NOTICE ); // avoid notice
require_once 'dbconfig.php';
if(isset($_POST['btnsave']))
{
$username = $_POST['user_name'];// user name
$userjob = $_POST['user_job'];// user email
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if(empty($username)){
$errMSG = "Please Enter Username.";
}
else if(empty($userjob)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($imgFile)){
$errMSG = "Please Select Image File.";
}
else
{
$upload_dir = 'user_images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get
image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid
extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
// allow valid image file formats
if(in_array($imgExt, $valid_extensions)){
// Check file size '5MB'
if($imgSize < 5000000)
{
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Sorry, your file is too large.";
}
}
else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
editform.php
editing form is simple like an insert form is, the complete code is given in the downloadable
file. while editing a record we have to fetch selected record from database, if image is
selected to edit then old image will be deleted and new image will be uploaded, here is the
only PHP script.
<?php
error_reporting( ~E_NOTICE );
require_once 'dbconfig.php';
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $DB_con->prepare('SELECT userName, userProfession, userPic
FROM tbl_users WHERE userID =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: index.php");
}
if(isset($_POST['btn_save_updates']))
{
$username = $_POST['user_name'];// user name
$userjob = $_POST['user_job'];// user email
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = 'user_images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get
image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid
extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['userPic']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else
{
// if no image selected the old image remain as it is.
$userpic = $edit_row['userPic']; // old image from database
}
}
}
?>
now the next step is record displaying along with image, well using bootstrap it easy to create
an image gallery let's have a look at the script.
index.php
within div tag class="row" an image gallery thumbnail will be generated from users table.
<div class="row">
<?php
$stmt = $DB_con->prepare('SELECT userID, userName, userProfession, userPic
FROM tbl_users ORDER BY userID DESC');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="col-xs-3">
<p class="page-header"><?php echo $userName." / ".
$userProfession; ?></p>
<img src="user_images/<?php echo $row['userPic']; ?>" class="imgrounded" width="250px" height="250px" />
<p class="page-header">
<span>
<a class="btn btn-info" href="editform.php?edit_id=<?php echo
$row['userID']; ?>" title="click for edit" onclick="return confirm('sure to
edit ?')"><span class="glyphicon glyphicon-edit"></span> Edit</a>
<a class="btn btn-danger" href="?delete_id=<?php echo $row['userID']; ?
>" title="click for delete" onclick="return confirm('sure to
delete ?')"><span class="glyphicon glyphicon-remove-circle"></span>
Delete</a>
</span>
</p>
</div>
<?php
}
}
else
{
?>
<div class="col-xs-12">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No
Data Found ...
</div>
</div>
<?php
}
?>
</div>
Download Script
that's it, here you can download this complete code and try in your localhost server, this was
just for beginners (beginner level) hence we can also create file uploading class to avoid
reuse of file uploading and we can also use Object Oriented way to achieve the same, hope
you like it. please do share.
Download Script
dbconfig.php
as usual simple database configuration file with PDO extension.
<?php
$db_host
$db_name
$db_user
$db_pass
=
=
=
=
"localhost";
"jquery_crud";
"root";
"";
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,
$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
index.php
i know it looks little lengthy but to use bootstrap design and jquery functions we have to add,
contains code which displays MySQL employee records from the table, little jQuery i have
used here it will used to load insert, update form directly without page refresh, MySQL
records will be displayed within jQuery Datatable.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert, Update, Delete using jQuery, PHP and MySQL</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"
media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet"
media="screen">
<link href="assets/datatables.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="assets/jquery-1.11.3jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn-view").hide();
$("#btn-add").click(function(){
$(".content-loader").fadeOut('slow', function()
{
$(".content-loader").fadeIn('slow');
$(".content-loader").load('add_form.php');
$("#btn-add").hide();
$("#btn-view").show();
});
});
$("#btn-view").click(function(){
$("body").fadeOut('slow', function()
$("body").load('index.php');
$("body").fadeIn('slow');
window.location.href="index.php";
});
});
});
</script>
</head>
<body>
<div class="container">
<h2 class="form-signin-heading">Employee Records.</h2><hr />
<button class="btn btn-info" type="button" id="btn-add"> <span
class="glyphicon glyphicon-pencil"></span> Add Employee</button>
<button class="btn btn-info" type="button" id="btn-view"> <span
class="glyphicon glyphicon-eye-open"></span> View Employee</button>
<hr />
<div class="content-loader">
<table cellspacing="0" width="100%" id="example" class="table
table-striped table-hover table-responsive">
<thead>
<tr>
<th>Emp ID</th>
<th>Emp Name</th>
<th>department</th>
<th>salary</th>
<th>edit</th>
<th>delete</th>
</tr>
</thead>
<tbody>
<?php
require_once 'dbconfig.php';
$stmt = $db_con->prepare("SELECT * FROM tbl_employees ORDER BY
emp_id DESC");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['emp_id']; ?></td>
<td><?php echo $row['emp_name']; ?></td>
<td><?php echo $row['emp_dept']; ?></td>
<td><?php echo $row['emp_salary']; ?></td>
<td align="center">
<a id="<?php echo $row['emp_id']; ?>" class="edit-link" href="#"
title="Edit">
<img src="edit.png" width="20px" />
</a></td>
<td align="center"><a id="<?php echo $row['emp_id']; ?>" class="deletelink" href="#" title="Delete">
add_form.php
simple html form to insert employee records contains three text box to enter employee name,
department and salary, it will be loaded within "index.php" by clicking "add employee"
button.
<style type="text/css">
#display{
display:none;
}
</style>
<div id="display">
<!-- here message will be displayed -->
</div>
<td>Employee Name</td>
<td><input type='text' name='emp_name' class='form-control'
placeholder='EX : john doe' required /></td>
</tr>
<tr>
<td>Employee Department</td>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-save"
id="btn-save">
<span class="glyphicon glyphicon-plus"></span> Save this Record
</button>
</td>
</tr>
</table>
</form>
create.php
this will insert a new record using jQuery into tbl_employees, on submit button click #empSaveForm form will be submitted using jQuery.
<?php
require_once 'dbconfig.php';
if($_POST)
{
$emp_name = $_POST['emp_name'];
$emp_dept = $_POST['emp_dept'];
$emp_salary = $_POST['emp_salary'];
try{
$stmt = $db_con->prepare("INSERT INTO
tbl_employees(emp_name,emp_dept,emp_salary) VALUES(:ename, :edept,
:esalary)");
$stmt->bindParam(":ename", $emp_name);
$stmt->bindParam(":edept", $emp_dept);
$stmt->bindParam(":esalary", $emp_salary);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
?>
}
catch(PDOException $e){
echo $e->getMessage();
}
edit_form.php
to fetch editable data from index.php and the data will be set within the following text box to
update, this will loaded too within index.php file in #container div, this jquery code will set
QueryString to edit_form.php : $(".content-loader").load('edit_form.php?
edit_id='+edit_id);
<?php
include_once 'dbconfig.php';
if($_GET['edit_id'])
{
$id = $_GET['edit_id'];
$stmt=$db_con->prepare("SELECT * FROM tbl_employees WHERE emp_id=:id");
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<style type="text/css">
#dis{
display:none;
}
</style>
<div id="dis">
</div>
<form method='post' id='emp-UpdateForm' action='#'>
<table class='table table-bordered'>
<input type='hidden' name='id' value='<?php echo $row['emp_id']; ?>' />
<tr>
<td>Employee Name</td>
<td><input type='text' name='emp_name' class='form-control'
value='<?php echo $row['emp_name']; ?>' required></td>
</tr>
<tr>
<td>Employee Department</td>
<td><input type='text' name='emp_dept' class='form-control'
value='<?php echo $row['emp_dept']; ?>' required></td>
</tr>
<tr>
<td>Employee Salary</td>
<td><input type='text' name='emp_salary' class='form-control'
value='<?php echo $row['emp_salary']; ?>' required></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-update"
id="btn-update">
<span class="glyphicon glyphicon-plus"></span> Save Updates
</button>
</td>
</tr>
</table>
</form>
update.php
simple file which will update the selected row from the "edit_form.php" and this will be
loaded too via a jQuery on submit function.
<?php
require_once 'dbconfig.php';
if($_POST)
{
$id = $_POST['id'];
$emp_name = $_POST['emp_name'];
$emp_dept = $_POST['emp_dept'];
$emp_salary = $_POST['emp_salary'];
$stmt = $db_con->prepare("UPDATE tbl_employees SET emp_name=:en,
emp_dept=:ed, emp_salary=:es WHERE emp_id=:id");
$stmt->bindParam(":en", $emp_name);
$stmt->bindParam(":ed", $emp_dept);
$stmt->bindParam(":es", $emp_salary);
$stmt->bindParam(":id", $id);
if($stmt->execute())
{
echo "Successfully updated";
}
else{
echo "Query Problem";
}
}
?>
delete.php
this file will delete rows from mysql - a simple code loaded via jQuery and delete rows from
mysql without page refresh. id will be get through this function : $.post('delete.php',
{'del_id':del_id}
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("DELETE FROM tbl_employees WHERE emp_id=:id");
$stmt->execute(array(':id'=>$id));
}
?>
crud.js
finally here is the complete jQuery file which will responsible to perform Insert, Update and
Delete contains only jQuery/JavaScript code.
// JavaScript Document
$(document).ready(function(){
/* Data Insert Starts Here */
$(document).on('submit', '#emp-SaveForm', function() {
$.post("create.php", $(this).serialize())
.done(function(data){
$("#dis").fadeOut();
$("#dis").fadeIn('slow', function(){
$("#dis").html('<div class="alert alert-info">'+data+'</div>');
$("#emp-SaveForm")[0].reset();
});
});
return false;
});
/* Data Insert Ends Here */
/* Update Record */
$(document).on('submit', '#emp-UpdateForm', function() {
$.post("update.php", $(this).serialize())
.done(function(data){
$("#dis").fadeOut();
$("#dis").fadeIn('slow', function(){
$("#dis").html('<div class="alert alert-info">'+data+'</div>');
$("#emp-UpdateForm")[0].reset();
$("body").fadeOut('slow', function()
{
$("body").fadeOut('slow');
window.location.href="index.php";
});
});
});
return false;
});
/* Update Record */
});
if you have any query regarding this tutorial fill free to contact me, download this jQuery
Add, Update, Delete tutorial and try it, that's it isn't it simple :)
See Demo
Download Script
dbconfig.php
Database configuration file, modify username, password and database values as
per your need.
<?php
$db_host
$db_name
$db_user
$db_pass
=
=
=
=
"localhost";
"dbregistration";
"root";
"";
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,
$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
create a new file and save it as index.php with the following code, this is our
main login page contains html user friendly login form which will accepts email,
password and of course validation is must so validation is there.
<div class="signin-form">
<div class="container">
<form class="form-signin" method="post" id="login-form">
<h2 class="form-signin-heading">Log In to WebApp.</h2><hr />
<div id="error">
<!-- error will be shown here ! -->
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email
address" name="user_email" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password"
name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-login"
id="btn-login">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
</div>
</form>
</div>
</div>
login_process.php
Contains only PHP code, this will verify email and password values in database,
this file will work silently at back-end and call via $.ajax() method using jQuery
code. if the login was success it gives ok message or if fails it will print wrong
details message.
<?php
session_start();
require_once 'dbconfig.php';
if(isset($_POST['btn-login']))
{
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$password = md5($user_password);
try
{
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE
user_email=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
$_SESSION['user_session'] = $row['user_id'];
}
else{
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Script.js
JavaScript/jQuery code which is responsible to do all the things silently, this will
call "login_process.php" through $.ajax() method and id "response" is ok then it
will redirect to the home page, if not it will display appropriate message within
"#error" div. this script is completed with proper validation.
$('document').ready(function()
{
/* validation */
$("#login-form").validate({
rules:
{
password: {
required: true,
},
user_email: {
required: true,
email: true
},
},
messages:
{
password:{
required: "please enter your password"
},
user_email: "please enter your email address",
},
submitHandler: submitForm
});
/* validation */
/* login submit */
function submitForm()
{
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'login_process.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('<span class="glyphicon glyphicontransfer"></span> sending ...');
},
success : function(response)
{
if(response=="ok"){
$("#btn-login").html('<img src="btn-ajax-loader.gif" />
Signing In ...');
setTimeout(' window.location.href = "home.php"; ',4000);
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span
class="glyphicon glyphicon-info-sign"></span> '+response+' !
</div>');
$("#btn-login").html('<span class="glyphicon glyphicon-login"></span> Sign In');
});
}
}
});
return false;
}
/* login submit */
});
home.php
this is our members home page and only members can access it, this file will
opened via ajax, and if session is empty it will redirect to the login/index page.
<?php
session_start();
if(!isset($_SESSION['user_session']))
{
header("Location: index.php");
}
include_once 'dbconfig.php';
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid");
$stmt->execute(array(":uid"=>$_SESSION['user_session']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form using jQuery Ajax and PHP MySQL</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"
media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet"
media="screen">
<link href="style.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Hello '<?php echo $row['user_name']; ?></strong> Welcome to the
members page.
</div>
</div>
</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
logout.php
destroy the session to logout the user and redirects to the login/index page.
<?php
session_start();
unset($_SESSION['user_session']);
if(session_destroy())
{
header("Location: index.php");
}
?>
that's it, we have created here a simple login script with Ajax, jQuery, PHP,
MySQL with BootStrap design, well this is a continuation part of my previously
posted tutorial. hope you like it.
Download Script
there are only 3 files we need for this tutorial, simple HTML form to accept valid image file,
php file to upload selected image to the server side and javascript code to upload image easily
without reloading page and to view the uploaded file into the particular div.
index.php
simple file contains only html form to accept image file to upload and send the request to the
PHP file called "ajaxupload.php" via ajax() method.
<!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Easy Ajax Image Upload with jQuery and PHP - codingcage.com</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.3jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
ajaxupload.php
this file contains only PHP code which will upload an image to the directory "uploads/" via
ajax, here i have given the validation for the image and it will upload only valid extension
images.
<?php
}
else
{
echo 'invalid file';
}
}
?>
script.js
Simple jQuery/JavaScript code to upload and view image without page refresh. using
$.ajax() method an image file wil be send to the "ajaxupload.php" file and file will be
uploaded and viewed at the same time.
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
that's it, how it becomes easy to upload an image to the server via ajax code, feel free to
contact me regarding this tutorial, hope you like it.
Download Script
Configure The "php.ini" File
open your php.ini file and search for following keys and make some changes as i
change like below :
1 . file_uploads = On
2 . upload_max_filesize = 50M
upload_max_filesize helps you to maximize file uploading size, by default it is
2, you can maximize as your need.
Read also : File uploading and View Script with PHP & MySQL
The html form :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
Make Sure :
<head>
<title>File Uploading With PHP and MySql</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
copy-paste the above script and try to upload any file, You can use this for
Uploading image's ,PDF's,MP3,Video, Doc any file types make sure you change
the necessary parts in the script.
that's it
Download Script
Database configuration.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the
server');
mysql_select_db($dbname) or die('database selection problem');
above html form sends the data to the following PHP script and joining this html
and php script you can easily upload files to the database .
upload.php
<?php
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
move_uploaded_file($file_loc,$folder.$file);
$sql="INSERT INTO tbl_uploads(file,type,size)
VALUES('$file','$file_type','$file_size')";
mysql_query($sql);
}
?>
<?php
$sql="SELECT * FROM tbl_uploads";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<tr>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['size'] ?></td>
<td><a href="uploads/<?php echo $row['file'] ?>"
target="_blank">view file</a></td>
</tr>
<?php
}
?>
</table>
that's it
Complete script.
dbconfig.php
?<php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the
server');
mysql_select_db($dbname) or die('database selection problem');
?>
index.php
First file with Html form which select the file from client to be upload.
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />
<?php
if(isset($_GET['success']))
{
?>
upload.php this is the main PHP Script of this tutorial which uploads the file to
the server.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(file,type,size)
VALUES('$final_file','$file_type','$new_size')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
view.php
this file shows the uploaded file from the database.
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
<table width="80%" border="1">
<tr>
<th colspan="4">your uploads...<label><a href="index.php">upload new
files...</a></label></th>
</tr>
<tr>
<td>File Name</td>
<td>File Type</td>
<td>File Size(KB)</td>
<td>View</td>
</tr>
<?php
$sql="SELECT * FROM tbl_uploads";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<tr>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['size'] ?></td>
<td><a href="uploads/<?php echo $row['file'] ?>"
target="_blank">view file</a></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
style.css
and last but not the least stylesheet that makes beautify all the pages.
@charset "utf-8";
/* CSS Document */
*
{
padding:0;
margin:0;
}
body
{
background:#fff;
font-family:Georgia, "Times New Roman", Times, serif;
text-align:center;
}
#header
{
background:#00a2d1;
width:100%;
height:50px;
color:#fff;
font-size:36px;
font-family:Verdana, Geneva, sans-serif;
}
#body
{
margin-top:100px;
}
#body table
{
margin:0 auto;
position:relative;
bottom:50px;
}
table td,th
{
padding:20px;
border: solid #9fa8b0 1px;
border-collapse:collapse;
}
#footer
{
text-align:center;
position:absolute;
left:0;
right:0;
margin:0 auto;
bottom:50px;
}
Download Script
Directory
our directory will be as follow :
bootstrap/
css/
bootstrap.min.css
js/
bootstrap.min.js
fonts/
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
glyphicons-halflings-regular.ttf
glyphicons-halflings-regular.woff
add-data.php
class.crud.php
dbconfig.php
delete.php
edit-data.php
footer.php
header.php
index.php
dbconfig.php
Set the credentials for the database and make a new PDO connection if the connection fails
display the error . Next include the class.crud.php file and make an instance of it, pass in
the database object to the class to make use of the database.
<?php
$DB_host
$DB_user
$DB_pass
$DB_name
=
=
=
=
"localhost";
"root";
"";
"dbpdo";
try
{
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,
$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
include_once 'class.crud.php';
$crud = new crud($DB_con);
?>
class.crud.php
this is the main class file which contains code for database operations.
create() and update() functions are in try/catch block to handle exceptions.
dataview() function selects the whole records from database table.
paging() function sets the QueryString like page_no=number.
paginglink() function creates the paging number links with previoue and next feature.
all the CRUD and Pagination operations are done by this file.
<?php
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function create($fname,$lname,$email,$contact)
{
try
{
$stmt = $this->db->prepare("INSERT INTO
tbl_users(first_name,last_name,email_id,contact_no) VALUES(:fname,
:lname, :email, :contact)");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":contact",$contact);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function getID($id)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
public function update($id,$fname,$lname,$email,$contact)
{
try
{
$stmt=$this->db->prepare("UPDATE tbl_users SET first_name=:fname,
last_name=:lname,
email_id=:email,
contact_no=:contact
WHERE id=:id ");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":contact",$contact);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM tbl_users WHERE id=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
/* paging */
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['first_name']); ?></td>
<td><?php print($row['last_name']); ?></td>
<td><?php print($row['email_id']); ?></td>
<td><?php print($row['contact_no']); ?></td>
<td align="center">
<a href="edit-data.php?edit_id=<?php print($row['id']); ?
>"><i class="glyphicon glyphicon-edit"></i></a>
</td>
<td align="center">
<a href="delete.php?delete_id=<?php print($row['id']); ?
>"><i class="glyphicon glyphicon-remove-circle"></i></a>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><ul class="pagination"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<li><a href='".$self."?page_no=1'>First</a></li>";
echo "<li><a href='".$self."?page_no=".$previous."'>Previous</a></li>";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".
$i."</a></li>";
}
else
{
echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<li><a href='".$self."?page_no=".$next."'>Next</a></li>";
echo "<li><a href='".$self."?page_no=".
$total_no_of_pages."'>Last</a></li>";
}
?></ul><?php
}
}
/* paging */
}
layouts
To reduce and make it less our code, we will create these two template files: header.php,
footer.php
header.php
This header.php file will be included at the beginning of all files so that we wont have to
write the same header codes every-time. this file contains bootstrap file links.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PDO OOP CRUD using Bootstrap</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"
media="screen">
</head>
<body>
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="http://www.codingcage.com"
title='Programming Blog'>Coding Cage</a>
<a class="navbar-brand"
href="http://www.codingcage.com/search/label/CRUD">CRUD</a>
<a class="navbar-brand"
href="http://www.codingcage.com/search/label/PDO">PDO</a>
<a class="navbar-brand"
href="http://www.codingcage.com/search/label/jQuery">jQuery</a>
</div>
</div>
</div>
footer.php
This footer.php file will be included at the end of all files so that we wont have to write the
same footer codes every-time.
<div class="container">
<div class="alert alert-info">
<strong>tutorial !</strong> <a href="http://www.codingcage.com/">Coding
Cage</a>!
</div>
</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
index.php
this file will show the records from the mysql database with pagination feature. the table
which are used in this file are created under bootstrap data table with class='table tablebordered table-responsive' it will make tables look pretty.
<?php
include_once 'dbconfig.php';
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<a href="add-data.php" class="btn btn-large btn-info"><i class="glyphicon
glyphicon-plus"></i> Add Records</a>
</div>
<div class="clearfix"></div><br />
<div class="container">
<table class='table table-bordered table-responsive'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Contact No</th>
<th colspan="2" align="center">Actions</th>
</tr>
<?php
$query = "SELECT * FROM tbl_users";
$records_per_page=3;
$newquery = $crud->paging($query,$records_per_page);
$crud->dataview($newquery);
?>
<tr>
<td colspan="7" align="center">
<div class="pagination-wrap">
<?php $crud->paginglink($query,$records_per_page); ?>
</div>
</td>
</tr>
</table>
</div>
<?php include_once 'footer.php'; ?>
add-data.php
now create a file and name it 'add-data.php' to get data from users to store into mysql
database.
in this file some appropriate message are given about data are insert or not with bootstrap
label.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email_id'];
$contact = $_POST['contact_no'];
if($crud->create($fname,$lname,$email,$contact))
{
header("Location: add-data.php?inserted");
}
else
{
header("Location: add-data.php?failure");
}
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<?php
if(isset($_GET['inserted']))
{
?>
<div class="container">
<div class="alert alert-info">
<strong>WOW!</strong> Record was inserted successfully <a
href="index.php">HOME</a>!
</div>
</div>
<?php
}
else if(isset($_GET['failure']))
{
?>
<div class="container">
<div class="alert alert-warning">
<strong>SORRY!</strong> ERROR while inserting record !
</div>
</div>
<?php
}
?>
<div class="clearfix"></div><br />
<div class="container">
<form method='post'>
<table class='table table-bordered'>
<tr>
<td>First Name</td>
<td><input type='text' name='first_name' class='form-control'
required></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' name='last_name' class='form-control'
required></td>
</tr>
<tr>
<td>Your E-mail ID</td>
<td><input type='text' name='email_id' class='form-control'
required></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type='text' name='contact_no' class='form-control'
required></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-save">
<span class="glyphicon glyphicon-plus"></span> Create New Record
</button>
<a href="index.php" class="btn btn-large btn-success"><i
class="glyphicon glyphicon-backward"></i> Back to index</a>
</td>
</tr>
</table>
</form>
</div>
<?php include_once 'footer.php'; ?>
edit-data.php
after creating a data insert form, this file updates the users data and the update operation are
done by update() function which are define in 'class.crud.php' class file
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
$id = $_GET['edit_id'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email_id'];
$contact = $_POST['contact_no'];
if($crud->update($id,$fname,$lname,$email,$contact))
{
$msg = "<div class='alert alert-info'>
<strong>WOW!</strong> Record was updated successfully <a
href='index.php'>HOME</a>!
</div>";
}
else
{
$msg = "<div class='alert alert-warning'>
if(isset($_GET['edit_id']))
{
$id = $_GET['edit_id'];
extract($crud->getID($id));
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($msg))
{
echo $msg;
}
?>
</div>
<div class="clearfix"></div><br />
<div class="container">
<form method='post'>
<table class='table table-bordered'>
<tr>
<td>First Name</td>
<td><input type='text' name='first_name' class='form-control'
value="<?php echo $first_name; ?>" required></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' name='last_name' class='form-control'
value="<?php echo $last_name; ?>" required></td>
</tr>
<tr>
<td colspan="2">
</div>
<?php include_once 'footer.php'; ?>
delete.php
this file contains code for data delete operation using delete() function by passing id
argument's value of selected data and row and by pressing the delete button the record will be
deleted and message will be given that the record was deleted.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-del']))
{
$id = $_GET['delete_id'];
$crud->delete($id);
header("Location: delete.php?deleted");
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($_GET['deleted']))
{
?>
<div class="alert alert-success">
<strong>Success!</strong> record was deleted...
</div>
<?php
}
else
{
?>
<div class="alert alert-danger">
<strong>Sure !</strong> to remove the following record ?
</div>
<?php
}
?>
</div>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($_GET['delete_id']))
{
?>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Gender</th>
</tr>
<?php
$stmt = $DB_con->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$_GET['delete_id']));
while($row=$stmt->fetch(PDO::FETCH_BOTH))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['first_name']); ?></td>
<td><?php print($row['last_name']); ?></td>
<td><?php print($row['email_id']); ?></td>
<td><?php print($row['contact_no']); ?></td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
</div>
<div class="container">
<p>
<?php
if(isset($_GET['delete_id']))
{
?>
<form method="post">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<button class="btn btn-large btn-primary" type="submit" name="btndel"><i class="glyphicon glyphicon-trash"></i> YES</button>
<a href="index.php" class="btn btn-large btn-success"><i
class="glyphicon glyphicon-backward"></i> NO</a>
</form>
<?php
}
else
{
?>
<a href="index.php" class="btn btn-large btn-success"><i
class="glyphicon glyphicon-backward"></i> Back to index</a>
<?php
}
?>
</p>
</div>
<?php include_once 'footer.php'; ?>
thats it we have created here Simple PDO CRUD Operation using OOP with Bootstrap
framework with pagination feature.
download the script by clicking following link and try it in your projects.
Feel free to comment your suggestions regarding this tutorial.
Download Script
Read also : Add, Update and Delete Example using jQuery and PHP
-add-data.php
-edit_mul.php
-update_mul.php
-delete_mul.php
dbcon.php
contains simple database configuration code with MySQLi.
<?php
$DB_host
$DB_user
$DB_pass
$DB_name
=
=
=
=
"localhost";
"root";
"";
"dbmultiple";
index.php
this is main index page which displays all the records from "users" table along
with checkbox for each record, and by selecting the multiple checkbox user can
update or delete the selected multiple records.
<?php
include_once 'dbcon.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multiple Insert, Update, Delete(CRUD) using PHP & MySQLi</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="jquery.js" type="text/javascript"></script>
<script src="js-script.js" type="text/javascript"></script>
</head>
<body>
<form method="post" name="frm">
<table width="50%" align="center" border="0">
<tr>
<td colspan="3"><a href="generate.php">add new records...</a></td>
</tr>
<tr>
<th>##</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<?php
$res = $MySQLiconn->query("SELECT * FROM users");
$count = $res->num_rows;
if($count > 0)
while($row=$res->fetch_array())
{
?>
<tr>
<td><input type="checkbox" name="chk[]" class="chk-box" value="<?php
echo $row['id']; ?>" /></td>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="3"> No Records Found ...</td>
</tr>
<?php
}
?>
<?php
if($count > 0)
{
?>
<tr>
<td colspan="3">
<label><input type="checkbox" class="select-all" /> Check / Uncheck
All</label>
<label id="actions">
<span style="word-spacing:normal;"> with selected :</span>
<span><img src="edit.png" onClick="edit();" alt="edit" />edit</span>
<span><img src="delete.png" onClick="delete_rec();"
alt="delete" />delete</span>
</label>
</td>
</tr>
<?php
}
?>
</table>
</form>
</body>
</html>
multiple insert
generate.php
contains simple HTML form which let's you to enter number of records to input,
ex 1 ,2 ,4, and accepts only two digit number, after inputting the number it will
redirects you to "add-data.php" which will create multiple input tags to insert the
data.
<link rel="stylesheet" href="style.css" type="text/css" />
add-data.php
this is the main file which helps you to insert multiple values as your choice, and
the rest process was done in "for()" loop.
<?php
error_reporting(0);
include_once 'dbcon.php';
if(isset($_POST['save_mul']))
{
$total = $_POST['total'];
for($i=1; $i<=$total; $i++)
{
$fn = $_POST["fname$i"];
$ln = $_POST["lname$i"];
$sql="INSERT INTO users(first_name,last_name) VALUES('".$fn."','".
$ln."')";
$sql = $MySQLiconn->query($sql);
}
if($sql)
{
?>
<script>
alert('<?php echo $total." records was inserted !!!"; ?>');
window.location.href='index.php';
</script>
<?php
}
else
{
?>
<script>
}
}
?>
<link rel="stylesheet" href="style.css" type="text/css" />
<div class="container">
<?php
if(isset($_POST['btn-gen-form']))
{
?>
<form method="post">
<input type="hidden" name="total" value="<?php echo
$_POST["no_of_rec"]; ?>" />
<table width="50%" align="center" border="0">
<tr>
<td colspan="3"><a href="generate.php">insert more records...</a></td>
</tr>
<tr>
<th>##</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<?php
for($i=1; $i<=$_POST["no_of_rec"]; $i++)
{
?>
<tr>
<td><?php echo $i; ?></td>
<td><input type="text" name="fname<?php echo $i; ?>"
placeholder="first name" /></td>
<td><input type="text" name="lname<?php echo $i; ?>"
placeholder="last name" /></td>
</tr>
<?php
}
?>
<tr>
<td colspan="3">
<button type="submit" name="save_mul">Insert all Records</button>
<a href="index.php" >Back to index</a>
</td>
</tr>
</table>
</form>
<?php
}
?>
</div>
Multiple Update
edit_mul.php
this file will create multiple input tags which have selected to be edited.
update_mul.php
this file will update the multiple selected records and redirects to the index page.
the update query will execute in "for()" loop as below.
<?php
include_once 'dbcon.php';
$id = $_POST['id'];
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$chk = $_POST['chk'];
$chkcount = count($id);
for($i=0; $i<$chkcount; $i++)
{
$MySQLiconn->query("UPDATE users SET first_name='$fn[$i]',
last_name='$ln[$i]' WHERE id=".$id[$i]);
}
header("Location: index.php");
?>
Multiple Delete
delete_mul.php
this is simple script to delete multiple records as above update or insert this
delete query will also execute in "for()" loop, and the rest script in this file is for
alerting the user.
<?php
error_reporting(0);
include_once 'dbcon.php';
$chk = $_POST['chk'];
$chkcount = count($chk);
if(!isset($chk))
{
?>
<script>
alert('At least one checkbox Must be Selected !!!');
window.location.href = 'index.php';
</script>
<?php
}
else
{
for($i=0; $i<$chkcount; $i++)
{
$del = $chk[$i];
$sql=$MySQLiconn->query("DELETE FROM users WHERE id=".$del);
}
if($sql)
{
?>
<script>
alert('<?php echo $chkcount; ?> Records Was Deleted !!!');
window.location.href='index.php';
</script>
<?php
}
else
{
?>
<script>
alert('Error while Deleting , TRY AGAIN');
window.location.href='index.php';
</script>
<?php
}
}
?>
js-script.js
javascript code for select / deselect all checkbox,
"edit_records()","delete_records()" function redirects user on specific page for
edit/delete on submit action.
// JavaScript Document
//
$('document').ready(function()
{
$(".select-all").click(function ()
{
$('.chk-box').attr('checked', this.checked)
});
$(".chk-box").click(function()
{
if($(".chk-box").length == $(".chk-box:checked").length)
{
$(".select-all").attr("checked", "checked");
}
else
{
$(".select-all").removeAttr("checked");
}
});
});
//
thats it we have created here Simple Multiple insert, Update and Delete CRUD
Download Script
this tutorial contains a folder called inc with PHP files like this :
index.php
add_records.php
edit_records.php
dbcrud.php
inc
-- class.crud.php
-- dbconfig.php
Database Configuration
dbconfig.php
this file handles database and server cofiguration and yes , with DB_con class with
constructor that works for all files.
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_NAME','dbtuts');
class DB_con
{
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die('error
connecting to server'.mysql_error());
mysql_select_db(DB_NAME, $conn) or die('error connecting to database>'.mysql_error());
}
}
?>
class.crud.php
this file contains a main class called CRUD which have inner functions like create , read,
update and delete, and this function name says what they do.
<?php
include_once 'dbconfig.php';
class CRUD
{
public function __construct()
{
$db = new DB_con();
}
public function create($fname,$lname,$city)
{
mysql_query("INSERT INTO users(first_name,last_name,user_city)
VALUES('$fname','$lname','$city')");
}
public function read()
{
return mysql_query("SELECT * FROM users");
}
public function delete($id)
}
public function update($fname,$lname,$city,$id)
{
mysql_query("UPDATE users SET first_name='$fname', last_name='$lname',
user_city='$city' WHERE user_id=".$id);
}
}
?>
these are the most important files for handle crud operations and works silently for all the
operations.
explained :
above html form contains all the fields the users table has.
Put the following script just above html form.
<?php
include_once 'inc/class.crud.php';
$crud = new CRUD();
if(isset($_POST['save']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
// insert
$crud->create($fname,$lname,$city);
// insert
}
?>
script explained :
including the class.crud.php we can use it's create() function to insert data.
here i shown you that how to use oops in different way to insert, select, update and delete
data from mysql. hope it would be helpful to you... that's it...
Complete Script
inc/dbconfig.php
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_NAME','dbtuts');
class DB_con
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die('error
connecting to server'.mysql_error());
mysql_select_db(DB_NAME, $conn) or die('error connecting to database>'.mysql_error());
}
}
?>
inc/class.crud.php
<?php
include_once 'dbconfig.php';
class CRUD
{
public function __construct()
{
$db = new DB_con();
}
public function create($fname,$lname,$city)
{
mysql_query("INSERT INTO users(first_name,last_name,user_city)
VALUES('$fname','$lname','$city')");
}
public function read()
{
return mysql_query("SELECT * FROM users");
}
public function delete($id)
{
mysql_query("DELETE FROM users WHERE user_id=".$id);
}
public function update($fname,$lname,$city,$id)
{
mysql_query("UPDATE users SET first_name='$fname', last_name='$lname',
user_city='$city' WHERE user_id=".$id);
}
}
?>
index.php
<?php
include_once 'inc/class.crud.php';
$crud = new CRUD();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>php oops crud tutorial part-2 by cleartuts</title>
</head>
<body>
<div id="header">
<label>php oops crud tutorial part-2 by cleartuts</label>
</div>
<center>
<table id="dataview">
<tr>
<td colspan="5"><a href="add_records.php">add new</a></td>
</tr>
<?php
$res = $crud->read();
if(mysql_num_rows($res)>0)
{
while($row = mysql_fetch_array($res))
{
?>
<tr>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['user_city']; ?></td>
<td><a href="edit_records.php?edt_id=<?php echo $row['user_id']; ?
>">edit</a></td>
<td><a href="dbcrud.php?del_id=<?php echo $row['user_id']; ?
>">delete</a></td>
</tr>
<?php
}
}
else
{
?><tr><td colspan="5">Nothing here... add some new</td></tr><?php
}
?>
</table>
<footer>
<label>Visit <a href="http://cleartuts.blogspot.com/">cleartuts</a> for
more tutorials...</label>
</footer>
</center>
</body>
</html>
add_records.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>php oops crud tutorial part-2 by cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>php oops crud tutorial part-2 by cleartuts</label>
</div>
<center>
<form method="post" action="dbcrud.php">
<table id="dataview">
<tr>
<td><input type="text" name="fname" placeholder="first name" /></td>
</tr>
<tr>
<td><input type="text" name="lname" placeholder="last name" /></td>
</tr>
<tr>
<td><input type="text" name="city" placeholder="city" /></td>
</tr>
<tr>
<td><button type="submit" name="save">save</button></td>
</tr>
</table>
</form>
</center>
</body>
</html>
edit_records.php
<?php
include_once 'inc/class.crud.php';
$crud = new CRUD();
if(isset($_GET['edt_id']))
{
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['edt_id']);
$row=mysql_fetch_array($res);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>php oops crud tutorial part-2 by cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>php oops crud tutorial part-2 by cleartuts</label>
</div>
<center>
<form method="post" action="dbcrud.php?edt_id=<?php echo $_GET['edt_id'] ?
>">
<table id="dataview">
<tr><td><input type="text" name="fname" placeholder="first name" value="<?
php echo $row['first_name'] ?>" /><br /></td></tr>
<tr><td><input type="text" name="lname" placeholder="last name" value="<?
php echo $row['last_name'] ?>" /></td></tr>
<tr><td><input type="text" name="city" placeholder="city" value="<?php echo
$row['user_city'] ?>" /></td></tr>
<tr><td><button type="submit" name="update">update</button></td></tr>
</table>
</form>
</table>
</center>
</body>
</html>
dbcrud.php
<?php
include_once 'inc/class.crud.php';
$crud = new CRUD();
if(isset($_POST['save']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
// insert
$crud->create($fname,$lname,$city);
// insert
header("Location: index.php");
}
if(isset($_GET['del_id']))
{
$id = $_GET['del_id'];
$crud->delete($id);
header("Location: index.php");
}
if(isset($_POST['update']))
{
$id = $_GET['edt_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
$crud->update($fname,$lname,$city,$id);
header("Location: index.php");
}
?>
style.css
@charset "utf-8";
/* CSS Document */
* { margin:0; padding:0; }
#header
{
text-align:center;
width:100%;
height:50px;
background:#00a2d1;
color:#f9f9f9;
font-weight:bolder;
font-family:Verdana, Geneva, sans-serif;
font-size:35px;
}
table,td
width:40%;
padding:15px;
border:solid #e1e1e1 1px;
font-family:Verdana, Geneva, sans-serif;
border-collapse:collapse;
}
#dataview
{
margin-top:100px;
position:relative;
bottom:50px;
}
#dataview input
{
width:100%;
height:40px;
border:0; outline:0;
font-family:Verdana, Geneva, sans-serif;
padding-left:10px;
}
#dataview button
{
width:200px;
height:40px;
border:0; outline:0;
font-family:Verdana, Geneva, sans-serif;
padding-left:10px;
}
footer { margin-top:50px; position:relative; bottom:50px; fontfamily:Verdana, Geneva, sans-serif; }
dbcrud.php this is the main PHP file which handles database connection data
insert , select , update and delete by creating such functions given in the
following php file.
dbcrud.php
<?php
class connect
{
public function connect()
{
mysql_connect("localhost","root");
mysql_select_db("dbtuts");
}
public function setdata($sql)
{
mysql_query($sql);
}
public function getdata($sql)
return mysql_query($sql);
}
public function delete($sql)
{
mysql_query($sql);
}
}
?>
CREATE : insert
To insert Data into mysql table we need to create html form containing all the
fields the users table has. and HTML code of insert form will be as follows.
<form method="post">
<table align="center">
<tr>
<td><input type="text" name="first_name" placeholder="First Name"
value="" required /></td>
</tr>
<tr>
<td><input type="text" name="last_name" placeholder="Last Name"
value="" required /></td>
</tr>
<tr>
<td><input type="text" name="city_name" placeholder="City" value=""
required /></td>
</tr>
<tr>
<td>
<button type="submit" name="btnsave"><strong>SAVE</strong></button></td>
</tr>
</table>
</form>
Using above form we can insert data with php oops as follow :
<?php
include_once 'dbcrud.php';
$con = new connect();
if(isset($_POST['btn-save']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city_name'];
$con->setdata("INSERT INTO users(first_name,last_name,user_city)
VALUES('$first_name','$last_name','$city')");
}
?>
READ : select
By using getdata() function we can fetch all data from table because it have
return type.
<?php
$res=$con->getdata("SELECT * FROM users");
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['user_city']; ?></td>
</tr>
<?php
}
}
?>
here i shown you that how to use oops to insert , select , update and delete data
from mysql.
that's it
complete oops crud script.
index.php
<?php
include_once 'dbcrud.php';
$con = new connect();
// delete condition
if(isset($_GET['delete_id']))
{
$con->delete("DELETE FROM users WHERE user_id=".$_GET['delete_id']);
header("Location: index.php");
}
// delete condition
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CRUD Operations Using PHP Oops - By Cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript">
function edt_id(id)
{
if(confirm('Sure to edit ?'))
{
window.location.href='insert-update.php?edit_id='+id;
}
}
function delete_id(id)
{
if(confirm('Sure to Delete ?'))
{
window.location.href='index.php?delete_id='+id;
}
}
</script>
</head>
<body>
<center>
<div id="header">
<div id="content">
<label>CRUD Operations Using PHP Oops - <a
href="http://cleartuts.blogspot.com" target="_blank">By
Cleartuts</a></label>
</div>
</div>
<div id="body">
<div id="content">
<table align="center">
<tr>
<th colspan="5"><a href="insert-update.php">add data here.</a></th>
</tr>
<th>First Name</th>
<th>Last Name</th>
<th>City Name</th>
<th colspan="2">Operations</th>
</tr>
<?php
$res=$con->getdata("SELECT * FROM users");
if(mysql_num_rows($res)==0)
{
?>
<tr>
<td colspan="5">Nothing Found Here !</td>
</tr>
<?php
}
else
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['user_city']; ?></td>
<td align="center"><a href="javascript:edt_id('<?php echo
$row['user_id']; ?>')"><img src="b_edit.png" alt="EDIT" /></a></td>
<td align="center"><a href="javascript:delete_id('<?php echo
$row['user_id']; ?>')"><img src="b_drop.png" alt="DELETE" /></a></td>
</tr>
<?php
}
}
?>
</table>
</div>
</div>
</center>
</body>
</html>
insert-update.php
<?php
include_once 'dbcrud.php';
$con = new connect();
// data insert code starts here.
if(isset($_POST['btn-save']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city_name'];
$con->setdata("INSERT INTO users(first_name,last_name,user_city)
VALUES('$first_name','$last_name','$city')");
header("Location: index.php");
}
// data insert code ends here.
// code for fetch user data via QueryString URL
if(isset($_GET['edit_id']))
{
$res=$con->getdata("SELECT * FROM users WHERE user_id=".$_GET['edit_id']);
$row=mysql_fetch_array($res);
}
// code for fetch user data via QueryString URL
// data update condition
if(isset($_POST['btn-update']))
{
$con->setdata("UPDATE users SET first_name='".$_POST['first_name']."',
last_name='".$_POST['last_name']."',
user_city='".$_POST['city_name']."'
WHERE user_id=".$_GET['edit_id']);
header("Location: index.php");
}
// data update condition
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CRUD Operations Using PHP and MySql - By Cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="header">
<div id="content">
<label>CRUD Operations Using PHP and MySql - By Cleartuts</label>
</div>
</div>
<div id="body">
<div id="content">
<form method="post">
<table align="center">
<tr>
<td align="center"><a href="index.php">back to main page</a></td>
</tr>
<tr>
<td><input type="text" name="first_name" placeholder="First Name"
value="<?php if(isset($row))echo $row['first_name']; ?>" required /></td>
</tr>
<tr>
<td><input type="text" name="last_name" placeholder="Last Name"
value="<?php if(isset($row))echo $row['last_name']; ?>" required /></td>
</tr>
<tr>
<td><input type="text" name="city_name" placeholder="City" value="<?php
if(isset($row))echo $row['user_city']; ?>" required /></td>
</tr>
<tr>
<td>
<?php
if(isset($_GET['edit_id']))
{
?><button type="submit" name="btnupdate"><strong>UPDATE</strong></button></td><?php
}
else
{
?><button type="submit" name="btnsave"><strong>SAVE</strong></button></td><?php
}
?>
</tr>
</table>
</form>
</div>
</div>
</center>
</body>
</html>
dbcrud.php
<?php
class connect
{
public function connect()
{
mysql_connect("localhost","root");
mysql_select_db("dbtuts");
}
public function setdata($sql)
{
mysql_query($sql);
}
public function getdata($sql)
{
return mysql_query($sql);
}
public function delete($sql)
{
mysql_query($sql);
}
}
?>
style.css
@charset "utf-8";
/* CSS Document */
*
{
margin:0;
padding:0;
}
body
{
background:#fff;
font-family:"Courier New", Courier, monospace;
}
#header
{
width:100%;
height:50px;
background:#00a2d1;
color:#f9f9f9;
font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size:35px;
text-align:center;
}
#header a
{
color:#fff;
text-decoration:blink;
}
#body
{
margin-top:50px;
}
table
width:80%;
font-family:Tahoma, Geneva, sans-serif;
font-weight:bolder;
color:#999;
margin-bottom:80px;
}
table a
{
text-decoration:none;
color:#00a2d1;
}
table,td,th
{
border-collapse:collapse;
border:solid #d0d0d0 1px;
padding:20px;
}
table td input
{
width:97%;
height:35px;
border:dashed #00a2d1 1px;
padding-left:15px;
font-family:Verdana, Geneva, sans-serif;
box-shadow:0px 0px 0px rgba(1,0,0,0.2);
outline:none;
}
table td input:focus
{
box-shadow:inset 1px 1px 1px rgba(1,0,0,0.2);
outline:none;
}
table td button
{
border:solid #f9f9f9 0px;
box-shadow:1px 1px 1px rgba(1,0,0,0.2);
outline:none;
background:#00a2d1;
padding:9px 15px 9px 15px;
color:#f9f9f9;
font-family:Arial, Helvetica, sans-serif;
font-weight:bolder;
border-radius:3px;
width:49.5%;
}
table td button:active
{
position:relative;
top:1px;
}
This is it. We have created a simple crud module capable to perform CRUD
( Create, Read, Update, Delete) operations using PHP Oops with MySql database.
Leave a comment if you have any queries or suggestions.
Database Crediantials.
Database name : dbtuts
Table name : users
Table Columns : user_id , first_name , last_name , user_city
Copy-Paste the following sql schema in your MySql database to create database and table.
CREATE DATABASE `dbtuts` ;
CREATE TABLE `dbtuts`.`users` (
`user_id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 25 ) NOT NULL ,
`last_name` VARCHAR( 25 ) NOT NULL ,
`user_city` VARCHAR( 45 ) NOT NULL
) ENGINE = InnoDB;
Now we need to create dbMySql.php file which contains host connection , database selection
and functions which are used to insert and select data from MySql users table.
dbMySql.php
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbtuts');
class DB_con
{
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost
connection problem'.mysql_error());
mysql_select_db(DB_NAME, $conn);
}
public function insert($fname,$lname,$city)
{
$res = mysql_query("INSERT users(first_name,last_name,user_city)
VALUES('$fname','$lname','$city')");
return $res;
}
public function select()
}
}
?>
script explained.
class DB_con has constructor function which creates the localhost connection and database
selection.
insert() function have some parameters like $fname , $lname and $city which accepts input
values from html form.
select() function fetch all the data from users table.
Data Insert
To insert Data into mysql table we need to create html form containing all the fields the users
table has. and HTML code of insert form will be as follows.
<html>
<head>
<body>
<form method="post">
<table align="center">
<tr>
<td><input type="text" name="first_name" placeholder="First Name"
/></td>
</tr>
<tr>
<td><input type="text" name="last_name" placeholder="Last Name" /></td>
</tr>
<tr>
<td><input type="text" name="city_name" placeholder="City" /></td>
</tr>
<tr>
<td>
<button type="submit" name="btnsave"><strong>SAVE</strong></button></td>
</tr>
</table>
</form>
</body>
</html>
$con->insert($fname,$lname,$city);
header("Location: index.php");
script explained.
This script contains variables like $fname , $lname and $city .
By including the dbMySql.php file in this script we can access and use all the functions of it,
by creating $con object.
$con->insert($fname,$lname,$city) inserts the value from html form into the users table.
Data Select
Next is how to select data from users table.
By using $con->select() function you can fetch data from users table like this.
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$res=$con->select();
while($row=mysql_fetch_row($res))
{
echo $row[1];
echo $row[2];
echo $row[3];
}
?>
script explained:
we included here dbMySql.php file in this script.
$con->select() function select all the rows from users table.
that's it
Complete Script with Design...
dbMySql.php
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbtuts');
class DB_con
{
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost
connection problem'.mysql_error());
mysql_select_db(DB_NAME, $conn);
}
public function insert($fname,$lname,$city)
{
$res = mysql_query("INSERT users(first_name,last_name,user_city)
VALUES('$fname','$lname','$city')");
return $res;
}
public function select()
{
$res=mysql_query("SELECT * FROM users");
return $res;
}
}
?>
index.php
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$table = "users";
$res=$con->select($table);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Data Insert and Select Data Using OOP - By Cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="header">
<div id="content">
<label>PHP Data Insert and Select Data Using OOP - By Cleartuts</label>
</div>
</div>
<div id="body">
<div id="content">
<table align="center">
<tr>
<th colspan="3"><a href="add_data.php">add data here...</a></th>
</tr>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
</tr>
<?php
while($row=mysql_fetch_row($res))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<div id="footer">
<div id="content">
<hr /><br/>
<label>for more tutorials and blog tips visit : <a
href="http://cleartuts.blogspot.com">cleartuts.com</a></label>
</div>
</div>
</center>
</body>
</html>
add_data.php
This script shows the values from tha users table.
<?php
include_once 'dbMySql.php';
$con = new DB_con();
<div id="body">
<div id="content">
<form method="post">
<table align="center">
<tr>
<td><input type="text" name="first_name" placeholder="First Name"
required /></td>
</tr>
<tr>
<td><input type="text" name="last_name" placeholder="Last Name"
required /></td>
</tr>
<tr>
<td><input type="text" name="city_name" placeholder="City" required
/></td>
</tr>
<tr>
<td>
<button type="submit" name="btnsave"><strong>SAVE</strong></button></td>
</tr>
</table>
</form>
</div>
</div>
</center>
</body>
</html>
style.css
This stylesheet makes beautify all the pages.
@charset "utf-8";
/* CSS Document */
*
{
margin:0;
padding:0;
}
#header
{
width:100%;
height:50px;
background:#00a2d1;
color:#f9f9f9;
font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size:35px;
text-align:center;
}
#header a
{
color:#fff;
text-decoration:blink;
}
#body
{
margin-top:50px;
}
table
width:40%;
font-family:Tahoma, Geneva, sans-serif;
font-weight:bolder;
color:#999;
margin-bottom:80px;
}
table a
{
text-decoration:none;
color:#00a2d1;
}
table,td,th
{
border-collapse:collapse;
border:solid #d0d0d0 1px;
padding:20px;
}
table td input
{
width:97%;
height:35px;
border:dashed #00a2d1 1px;
padding-left:15px;
font-family:Verdana, Geneva, sans-serif;
box-shadow:0px 0px 0px rgba(1,0,0,0.2);
outline:none;
}
table td input:focus
{
box-shadow:inset 1px 1px 1px rgba(1,0,0,0.2);
outline:none;
}
table td button
{
border:solid #f9f9f9 0px;
box-shadow:1px 1px 1px rgba(1,0,0,0.2);
outline:none;
background:#00a2d1;
padding:9px 15px 9px 15px;
color:#f9f9f9;
font-family:Arial, Helvetica, sans-serif;
font-weight:bolder;
border-radius:3px;
width:100%;
}
table td button:active
{
position:relative;
top:1px;
}
#footer
{
margin-top:50px;
position:relative;
bottom:30px;
font-family:Verdana, Geneva, sans-serif;
}
Download Script
Database Crediantials.
Here i am going to use Database Crediantials which was used in my previous tutorial.
Database name : dbtuts
Table name : users
Table Columns : user_id , first_name , last_name , user_city .
CREATE DATABASE `dbtuts` ;
CREATE TABLE `dbtuts`.`users` (
`user_id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 25 ) NOT NULL ,
`last_name` VARCHAR( 25 ) NOT NULL ,
`user_city` VARCHAR( 45 ) NOT NULL
) ENGINE = InnoDB;
class DB_con
{
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost
connection problem'.mysql_error());
mysql_select_db(DB_NAME, $conn);
}
public function select()
{
Script Explained:
__constructor() : this function connects the localhost server and database.
select() : Select data from users table.
delete() : function with $table and $id which is for MySql Delete Query.
update() : this function have four parameters with table name and table fields value.
Data Update
After data showing on the page create a file called edit_data.php and add the following code
just above the html edit data form.
edit_data.php
include_once 'dbMySql.php';
$con = new DB_con();
$table = "users";
if(isset($_GET['edit_id']))
{
$sql=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['edit_id']);
$result=mysql_fetch_array($sql);
}
// and update condition would be as follow ...
if(isset($_POST['btn-update']))
{
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$city = $_POST['city_name'];
$id=$_GET['edit_id'];
$res=$con->update($table,$id,$fname,$lname,$city);
}
Delete Data
Now create a new file called delete_data.php and put the following code into this file like this
:
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$table = "users";
if(isset($_GET['delete_id']))
{
$id=$_GET['delete_id'];
$res=$con->delete($table,$id);
}
?>
that's it
Complete Script :
dbMySql.php
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbtuts');
class DB_con
{
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost
connection problem'.mysql_error());
mysql_select_db(DB_NAME, $conn);
}
public function select()
{
$res=mysql_query("SELECT * FROM users");
return $res;
}
public function delete($table,$id)
{
$res = mysql_query("DELETE FROM $table WHERE user_id=".$id);
return $res;
}
public function update($table,$id,$fname,$lname,$city)
{
$res = mysql_query("UPDATE $table SET first_name='$fname',
last_name='$lname', user_city='$city' WHERE user_id=".$id);
return $res;
}
}
?>
index.php
contains html , php script to display data on this page with some javascript that confirms any
operation to be perform or not.
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$res=$con->select();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Data Update and Delete Using OOP - By Cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript">
function del_id(id)
{
if(confirm('Sure to delete this record ?'))
{
window.location='delete_data.php?delete_id='+id
}
}
function edit_id(id)
{
if(confirm('Sure to edit this record ?'))
{
window.location='edit_data.php?edit_id='+id
}
}
</script>
</head>
<body>
<center>
<div id="header">
<div id="content">
<label>PHP Data Update and Delete Using OOP - By Cleartuts</label>
</div>
</div>
<div id="body">
<div id="content">
<table align="center">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
<th colspan="2">edit/delete</th>
</tr>
<?php
while($row=mysql_fetch_row($res))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
<td align="center"><a href="javascript:edit_id(<?php echo
$row[0]; ?>)"><img src="b_edit.png" alt="EDIT" /></a></td>
<td align="center"><a href="javascript:del_id(<?php echo
$row[0]; ?>)"><img src="b_drop.png" alt="DELETE" /></a></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<div id="footer">
<div id="content">
<hr /><br/>
<label>for more tutorials and blog tips visit : <a
href="http://cleartuts.blogspot.com">cleartuts.com</a></label>
</div>
</div>
</center>
</body>
</html>
edit_data.php
contains html and php script to update data with javascript for redirection to the main page
and completion messege.
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$table = "users";
// data insert code starts here.
if(isset($_GET['edit_id']))
{
$sql=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['edit_id']);
$result=mysql_fetch_array($sql);
}
// data update code starts here.
if(isset($_POST['btn-update']))
{
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$city = $_POST['city_name'];
$id=$_GET['edit_id'];
$res=$con->update($table,$id,$fname,$lname,$city);
if($res)
{
?>
<script>
alert('Record updated...');
window.location='index.php'
</script>
<?php
}
else
{
?>
<script>
alert('error updating record...');
window.location='index.php'
</script>
<?php
}
}
// data update code ends here.
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Data Insert and Select Data Using OOP - By Cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="header">
<div id="content">
<label>PHP Data Insert and Select Data Using OOP - By Cleartuts</label>
</div>
</div>
<div id="body">
<div id="content">
<form method="post">
<table align="center">
<tr>
<td><input type="text" name="first_name" placeholder="First Name"
value="<?php echo $result['first_name']; ?>" /></td>
</tr>
<tr>
<td><input type="text" name="last_name" placeholder="Last Name"
value="<?php echo $result['last_name']; ?>" /></td>
</tr>
<tr>
<td><input type="text" name="city_name" placeholder="City" value="<?php
echo $result['user_city']; ?>" /></td>
</tr>
<tr>
<td>
<button type="submit" name="btnupdate"><strong>UPDATE</strong></button></td>
</tr>
</table>
</form>
</div>
</div>
</center>
</body>
</html>
delete_data.php
contains php and javascript , PHP for data delete action and javascript for alert and
redirection to the main page.
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$table = "users";
if(isset($_GET['delete_id']))
{
$id=$_GET['delete_id'];
$res=$con->delete($table,$id);
if($res)
{
?>
<script>
alert('Record Deleted ...')
window.location='index.php'
</script>
<?php
}
else
{
?>
<script>
alert('Record cant Deleted !!!')
window.location='index.php'
</script>
<?php
}
}
?>
style.css
to make beautify all the pages.
@charset "utf-8";
/* CSS Document */
*
{
margin:0;
padding:0;
}
#header
{
width:100%;
height:50px;
background:#00a2d1;
color:#f9f9f9;
font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size:35px;
text-align:center;
}
#header a
{
color:#fff;
text-decoration:blink;
}
#body
{
margin-top:50px;
}
table
{
width:40%;
font-family:Tahoma, Geneva, sans-serif;
font-weight:bolder;
color:#999;
margin-bottom:80px;
}
table a
{
text-decoration:none;
color:#00a2d1;
}
table,td,th
{
border-collapse:collapse;
border:solid #d0d0d0 1px;
padding:20px;
}
table td input
{
width:97%;
height:35px;
border:dashed #00a2d1 1px;
padding-left:15px;
font-family:Verdana, Geneva, sans-serif;
box-shadow:0px 0px 0px rgba(1,0,0,0.2);
outline:none;
}
table td input:focus
{
box-shadow:inset 1px 1px 1px rgba(1,0,0,0.2);
outline:none;
}
table td button
{
border:solid #f9f9f9 0px;
box-shadow:1px 1px 1px rgba(1,0,0,0.2);
outline:none;
background:#00a2d1;
padding:9px 15px 9px 15px;
color:#f9f9f9;
font-family:Arial, Helvetica, sans-serif;
font-weight:bolder;
border-radius:3px;
width:100%;
}
table td button:active
{
position:relative;
top:1px;
}
#footer
{
margin-top:50px;
position:relative;
bottom:30px;
font-family:Verdana, Geneva, sans-serif;
}
Download Script
Live Demo
Download Script
Database Design
the database used in this tutorial is "dbtest" and the table is users, so create dbtest in your
phpmyadmin and paste the following sql code to create users table.
--- Database: `mysqli_login`
--
dbconnect.php
this file contains code for connection using MySQLi extension, here's how you can use
MySQLi an improved extension with your MySQL Database.
<?php
$DBhost
$DBuser
$DBpass
$DBname
=
=
=
=
"localhost";
"root";
"";
"mysqli_login";
register.php
this is our registration/signup page for the new user and it will ask username, email and
password to enter, i have skipped here validation part and used HTML5 required client side
validations to validate the form and the form was created with bootstrap.
password_hash($upass, PASSWORD_DEFAULT); it will make password stronger than
MD5.
<?php
session_start();
if (isset($_SESSION['userSession'])!="") {
header("Location: home.php");
}
require_once 'dbconnect.php';
if(isset($_POST['btn-signup'])) {
$uname = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$upass = strip_tags($_POST['password']);
$uname = $DBcon->real_escape_string($uname);
$email = $DBcon->real_escape_string($email);
$upass = $DBcon->real_escape_string($upass);
$hashed_password = password_hash($upass, PASSWORD_DEFAULT);
// this function works only in PHP 5.5 or latest version
$check_email = $DBcon->query("SELECT email FROM tbl_users WHERE
email='$email'");
$count=$check_email->num_rows;
if ($count==0) {
{
alert-success'>
glyphicon-info-sign'></span>
alert-danger'>
glyphicon-info-sign'></span> error
} else {
signup">
<span class="glyphicon glyphicon-log-in"></span> Create
Account
</button>
<a href="index.php" class="btn btn-default"
style="float:right;">Log In Here</a>
</div>
</form>
</div>
</div>
</body>
</html>
index.php
this is our login page which will ask users to enter email and password to go the home page
which is members page, to use database we have to include "dbconnect.php" file. i have used
here password_verify($upass, $row['password']) to verify password this is new password
hashing functin and you have to use PHP5.5 to use this function.
<?php
session_start();
require_once 'dbconnect.php';
if (isset($_SESSION['userSession'])!="") {
header("Location: home.php");
exit;
}
if (isset($_POST['btn-login'])) {
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$email = $DBcon->real_escape_string($email);
$password = $DBcon->real_escape_string($password);
$query = $DBcon->query("SELECT user_id, email, password FROM tbl_users
WHERE email='$email'");
$row=$query->fetch_array();
$count = $query->num_rows; // if email/password are correct returns must
be 1 row
if (password_verify($password, $row['password']) && $count==1) {
$_SESSION['userSession'] = $row['user_id'];
header("Location: home.php");
} else {
$msg = "<div class='alert alert-danger'>
<span class='glyphicon glyphicon-info-sign'></span> Invalid
Username or Password !
</div>";
}
$DBcon->close();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"
media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet"
media="screen">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="signin-form">
<div class="container">
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-login"
id="btn-login">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
<a href="register.php" class="btn btn-default"
style="float:right;">Sign UP Here</a>
</div>
</form>
</div>
</div>
</body>
</html>
home.php
if user successfully logged in he will be redirected to this "home.php" page, this is members
page only registered users can access this page, contains bootstrap header with menu and one
link to logout.
<?php
session_start();
include_once 'dbconnect.php';
if (!isset($_SESSION['userSession'])) {
header("Location: index.php");
}
$query = $DBcon->query("SELECT * FROM tbl_users WHERE user_id=".
$_SESSION['userSession']);
$userRow=$query->fetch_array();
$DBcon->close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['email']; ?></title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"
media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet"
media="screen">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" datatoggle="collapse" data-target="#navbar" aria-expanded="false" ariacontrols="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://www.codingcage.com">Coding
Cage</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a
href="http://www.codingcage.com/2015/03/simple-login-and-signup-systemwith-php.html">Back to Article</a></li>
<li><a
href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
<li><a
href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphiconuser"></span> <?php echo $userRow['username']; ?></a></li>
<li><a href="logout.php?logout"><span class="glyphicon
glyphicon-log-out"></span> Logout</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container" style="margin-top:150px;text-align:center;fontfamily:Verdana, Geneva, sans-serif;font-size:35px;">
<a href="http://www.codingcage.com/">Coding Cage - Programming Blog</a><br
/><br />
<p>Tutorials on PHP, MySQL, Ajax, jQuery, Web Design and more...</p>
</div>
</body>
</html>
logout.php
simple page to logout the users and redirects to the login/index page. it will destroys the
current logged in users session.
<?php
session_start();
if (!isset($_SESSION['userSession'])) {
header("Location: index.php");
} else if (isset($_SESSION['userSession'])!="") {
header("Location: home.php");
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['userSession']);
header("Location: index.php");
}
That's it, we have covered here a simple login and registration system using PHP and
MySQLi, the reason behind posting this tutorial is, i got few emails regarding MySQLi login
and signup script, so i have posted it here. if you like it please share it with your social media
friends, thank you :)
Download Script
Read Also : How to Parse JSON Data using jQuery Ajax into HTML
Here is the sample MySQL Dump data which are used in this tutorial, run the following sql
query in your PHPMyAdmin it will create table with several records.
CREATE TABLE IF NOT EXISTS `tbl_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--- Dumping data for table `tbl_users`
-INSERT INTO `tbl_users` (`id`, `first_name`, `last_name`) VALUES
(1, 'John', 'Doe'),
(2, 'Jane', 'Doe'),
(3, 'John', 'Cena'),
(4, 'Dwayne', 'Johnson');
ok, now make a connection to mysql database using PDO extension here is the code
<?php
$DBhost
$DBuser
$DBpass
$DBname
=
=
=
=
"localhost";
"root";
"";
"dbjson";
try{
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
"AllUsers": [
{
"id": "1",
"first_name": "John",
"last_name": "Doe"
},
{
"id": "2",
"first_name": "Jane",
"last_name": "Doe"
},
{
"id": "3",
"first_name": "John",
"last_name": "Cena"
},
{
"id": "4",
"first_name": "Dwayne",
"last_name": "Johnson"
}
]
}
Final Code
here is the final code of above all small pieces..
<?php
require_once 'dbconfig.php';
$query = "SELECT * FROM tbl_users";
$stmt = $DBcon->prepare($query);
$stmt->execute();
$userData = array();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$userData['AllUsers'][] = $row;
}
echo json_encode($userData);
?>
Hope you like it, actually recently i had a work on JSON Apis, so i have decided share a
small piece of json code. and guys please keep visiting and do share it with your dev friends
that's it ...
Live Demo
Download Script
Demo Data
following is the demo mysql data for the tutorial purpose, we will convert these mysql rows
into json format, so copy paste the following data into your PHPMyAdmin.
--- Database: `codingcage`
--- ---------------------------------------------------------- Table structure for table `tbl_posts`
-CREATE TABLE IF NOT EXISTS `tbl_posts` (
Sample JavaScript
the following code is the complete javascript code which calls php file and and parse the json
data into html table. as i explained above $.getJSON() methods takes the url parameter
and calls the getjson.php file, and php file contains JSON data.
$(document).ready(function(){
var url="getjson.php";
$.getJSON(url,function(data){
console.log(data);
$.each(data.tutorials, function(i,post){
var newRow =
"<tr>"
+"<td>"+post.postTitle+"</td>"
+"<td><a href='"+post.postUrl+"'>Visit</a></td>"
+"</tr>" ;
$(newRow).appendTo("#json-data");
});
});
});
HTML table
HTML table, here in this table JSON data are going to be parsed and displayed. we need to
give the id of this table in the javascript part id="json-data"
<table id="json-data" class="table table-bordered table-hover">
<tr>
<th>Post Title</th>
<th>Post Url</th>
</tr>
</table>
require_once 'db.php';
$posts = array();
$query = "SELECT * FROM tbl_posts";
$stmt = $db_con->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
$posts['tutorials'][] = $row;
}
echo json_encode($posts);
Database Connection
<?php
$db_hostname = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "codingcage";
try{
"tutorials": [{
"postID": "1",
"postTitle": "Simple jQuery Add, Update, Delete with PHP and MySQL",
"postUrl": "http://goo.gl/IL6NTr"
}, {
"postID": "2",
"postTitle": "15 Free Bootstrap Admin Themes Demo and Download",
"postUrl": "http://goo.gl/1dBwEy"
}, {
"postID": "3",
"postTitle": "Easy Ajax Image Upload with jQuery, PHP",
"postUrl": "http://goo.gl/jXZ6LY"
}, {
"postID": "4",
"postTitle": "How to Send HTML Format eMails in PHP using PHPMailer",
"postUrl": "http://goo.gl/kQrzJP"
}, {
"postID": "5",
"postTitle": "Ajax Bootstrap Signup Form with jQuery PHP and MySQL",
"postUrl": "http://goo.gl/yxKrha"
}, {
"postID": "6",
"postTitle": "Submit PHP Form without Page Refresh using jQuery, Ajax",
"postUrl": "http://goo.gl/14vlBe"
}, {
"postID": "7",
"postTitle": "How to Convert MySQL Rows into JSON Format in PHP",
"postUrl": "http://goo.gl/qgOiwB"
}, {
"postID": "8",
"postTitle": "Designing Bootstrap Signup Form with jQuery Validation",
"postUrl": "http://goo.gl/nECERc"
}, {
"postID": "9",
"postTitle": "Upload, Insert, Update, Delete an Image using PHP MySQL",
"postUrl": "http://goo.gl/HRJrDD"
}, {
"postID": "10",
"postTitle": "Login Registration with Email Verification, Forgot Password
using PHP",
"postUrl": "http://goo.gl/O9FKN1"
}]
}
$.ajax({
url: 'getjson.php',
dataType: 'json',
})
.done(function(data){
console.log(data);
$.each(data.tutorials, function(i,post){
var newRow =
"<tr>"
+"<td>"+post.postTitle+"</td>"
+"<td><a href='"+post.postUrl+"'>Visit</a></td>"
+"</tr>" ;
$(newRow).appendTo("#json-data");
});
})
.fail(function(){
alert('fail parsing');
})
Hope, you guys like this post please do share with your friends, and do let me know if you
have any question related any tutorials.
that's it, Happy Coding :)
Halo semuanya..
Sekarang saya mau coba buat tutorial Bootstrap sederhana, namun bnyak sekali digunakan
dalam berbagai kasus pembuatan website. yaitu, bagaimana membuat form edit pada Modal
di twitter bootstrap. Penjelasan sederhananya, saat kita ingin mengedit suatu record data dan
mengklik button "edit", muncul modal dengan form edit didalamnya, namun di dalam form
input tersebut, sudah terisikan data-data berdasarakan "ID" data yang kita pilih..
Contoh Seperti gambar dibawah ini : Jika di klik button edit pada record no. 1 maka akan
muncul form edit dengan data kode pelanggan P-001.
Untuk membuat itu, ada beberapa cara yang bisa dilakukan. disini saya akan menggukan
script jQuery. Skr langsung aja kita coba
SCRIPT HTML
Link 1 <br>
<a data-toggle="modal" data-id="Gilang Sonar [Link Satu]" title="Add this
item" class="open-AddBookDialog btn btn-primary"
href="#addBookDialog">Button I</a>
<hr>
Link 2 <br>
<a data-toggle="modal" data-id="Gilang Sonar [Link Dua]" title="Add this
item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">
Button II
</a>
SCRIPT jQuery
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
});
Silahkan dicoba.. dan untuk data-id bisa kalian sesuaikan dengan data yang kalian buat
(diambil dari Fetching data dari database)
BERHUBUNG... ada yang protes krna gambar yang ane kasih diatas ga sama sama contoh di
live demonya,, nih saya update, saya kasih gambarnya.. Udah niat kan brooo??? hahahaha
Tampilan diatas lebih menarik bukan?, dibandingkan kita mengedit data dengan
tampilan standart.
Langkah Pertama
Dowload bootstrap disini , dan download jquery disini
Langkah Kedua
Extract file bootstrap dan jquery yang sobat download kedalam root aplikasi
sobat, root aplikasi saya di c:\xampp\htdocs\php7\modal, sesuaikan dengan
folder root yang sobat miliki.
Langkah Ketiga
Sobat buat database, database milik saya namanya dbphp7 kalau sobat terserah
mau buat apa namanya, dan buat tabel dengan nama modal
CREATE TABLE `modal` (
`modal_id` int(11) NOT NULL AUTO_INCREMENT,
`modal_name` varchar(255) DEFAULT NULL,
`description` text,
`date` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`modal_id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
Langkah Keempat
Setelah ketiga langka diatas sobat lakukan, ketiklah kode dibawah ini, simpan
dengan nama, index.php
<!doctype html>
<html lang="en">
<head>
<title>Aguzrybudy.com | Crud Menggunakan Modal Bootstrap (popup)</title>
<meta content="width=device-width, initial-scale=1.0, user-scalable=no,
minimum-scale=1.0, maximum-scale=1.0" name="viewport"/>
<meta content="Aguzrybudy" name="author"/>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>
Crud PHP 7 Menggunakan Modal Bootstrap (Popup)</h2>
<p>
Bootstrap Modal (Popup) By Aguzrybudy, Selasa 19 April 2016</p>
<p>
<a href="#" class="btn btn-success" data-target="#ModalAdd" datatoggle="modal">Add Data</a></p>
<table id="mytable" class="table table-bordered"><thead>
<th>No</th>
<th>Name</th>
<th>Description</th>
<th>Action</th>
</thead>
<?php
include "koneksi.php";
$no = 0;
$modal=mysqli_query($koneksi,"SELECT * FROM modal");
while($r=mysqli_fetch_array($modal)){
$no++;
?>
<tr>
<td><?php echo $no; ?></td>
<td><?php echo
$r['modal_name']; ?></td>
<td><?php echo $r['description']; ?></td>
<td>
<a href="#" class='open_modal' id='<?php echo $r['modal_id']; ?>'>Edit</a>
<a href="#" onclick="confirm_modal('proses_delete.php?&modal_id=<?php echo
$r['modal_id']; ?>');">Delete</a>
</td>
</tr>
<?php } ?> </table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".open_modal").click(function(e) {
var m = $(this).attr("id");
$.ajax({
url: "modal_edit.php",
type: "GET",
data : {modal_id: m,},
success: function (ajaxData){
$("#ModalEdit").html(ajaxData);
$("#ModalEdit").modal('show',{backdrop: 'true'});
}
});
});
});
</script>
<script type="text/javascript">
function confirm_modal(delete_url)
{
$('#modal_delete').modal('show', {backdrop: 'static'});
document.getElementById('delete_link').setAttribute('href' ,
delete_url);
}
</script>
</body>
</html>
Langkah Kelima
Buat file dengan nama modal_edit.php :
<?php
include "koneksi.php";
$modal_id=$_GET['modal_id'];
$modal=mysqli_query($koneksi,"SELECT * FROM modal WHERE
modal_id='$modal_id'");
while($r=mysqli_fetch_array($modal)){
?>
Langkah Keenam
Buat koneksi dabatase mysqli, simpan dengan nama koneksi.php
<?php
$host="localhost";
$user="root";
$pass="";
$database="dbphp7";
$koneksi=new mysqli($host,$user,$pass,$database);
if (mysqli_connect_errno()) {
trigger_error('Koneksi ke database gagal: ' . mysqli_connect_error(),
E_USER_ERROR);
}
?>
Langkah Ketujuh
Buat proses simpan data dengan nama proses_save.php
<?php
include "koneksi.php";
$modal_name = $_POST['modal_name'];
$description = $_POST['description'];
mysqli_query($koneksi,"INSERT INTO modal (modal_name,description) VALUES
('$modal_name','$description')");
header('location:index.php');
?>
Langkah Kedelapan
Buat proses edit data dengan nama proses_edit.php
<?php
include "koneksi.php";
$modal_id=$_POST['modal_id'];
$modal_name = $_POST['modal_name'];
$description = $_POST['description'];
$modal=mysqli_query($koneksi,"UPDATE modal SET modal_name =
'$modal_name',description = '$description' WHERE modal_id = '$modal_id'");
header('location:index.php');
?>
Langkah Kesembilan
Buat proses delete data dengan nama proses_delete.php
<?php
include "koneksi.php";
$modal_id=$_GET['modal_id'];
$modal=mysqli_query($koneksi,"Delete FROM modal WHERE
modal_id='$modal_id'");
header('location:index.php');
?>
Langkah Kesepuluh
Silahkan sobat test program yang sobat buat, jika berhasil maka indexnya akan
muncul seperti gambar dibawah ini .
Add Data
Edit Data
Delete Data
NB : Sobat harus download code dari link yang sudah saya siapkan dibawah ini,
karena kode diatas tidak lengkap.
Code diatas saya tulis menggunakan PHP 7.
sampai disini dulu tutorial dari saya , Semoga tutorial ini bermanfaat bagi sobat,
atas segala kekuranganya mohon dimaafkan dan di beri saran untuk file PDF
-NYA download disini dan jika sobat ingin code dari aplikasi diatas download dari
link dibawah ini.