Quantcast
Channel: Seegatesite.com
Viewing all 231 articles
Browse latest View live

Slim Framework Basic Tutorial For Beginner, A Micro Framework For PHP

$
0
0

Slim Framework is a Lightweight and powerful PHP framework. Maybe if you heard about a PHP framework that would come to your mind is learning again from the scratch. But I say no to Slim Framework. Armed with a brief knowledge about PHP you can implement the framework rapidly. Slim Framework does indeed deserve juxtaposed with large frameworks such as Laravel, CodeIgniter, etc. In addition to light, we can easily create APIs with PHP quickly.

What is Slim Framework?

Slim Framework built by Josh Lockhart, a senior developer of newmediacampaigns.com and he is “the man behind” PHP at The Right Way. According to Josh Lockhart, Slim Framework are:

“PHP micro framework that helps PHP developers quickly and easily write web applications and APIs. Think of it as a core set of tools with which a developer can build amazing things.”

Slim is a micro framework for more emphasis on basic needs such as creating a web application APIs (receiving an HTTP request and send the request along with the results of its response).

If you want to create CRUD applications with PHP for small-scale, this micro framework is very suitable to be used rather than using a fullstack framework.

The main advantages of the Slim framework are:

  • HTTP Router.
  • Middleware.
  • Dependency Injection.
  • PSR-7 Support

Slim Framework Installation

To find out more about the slim framework please visit the official website. The next step I will share how to install slim framework along with a simple example. To install Slim Framework using the composer. In this tutorial I will use ubuntu terminal:

Skip step installation of composer on ubuntu if you already have a composer

Run this script below on your ubuntu terminal
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

How to Install Slim Framework

composer require slim/slim “^3.0”

How To Use Slim Framework And How To Install It

After the download process is complete, you will find a “vendor” folder in the project directory. Until this stage, the installation has been successful. The next step is how to use the slim framework

How to use the slim framework

1. Make sure the folder structure on your project as follows

Slim Framework Structure Folder

2. Make index.php file in the public folder, and enter the following code:

<?php

require '../vendor/autoload.php';
$app = new \Slim\App;
$app->get('/profile/{name}', function($request, $response) {
 $name = $request->getAttribute('name');
 $response->getBody()->write("Welcome back $name");
 return $response;
});
$app->run();

In the script above, we use Slim Framework to create a route with a GET method that would capture a parameter of the URL. In order for the script work properly, don’t forget to add .htaccess file in the public folder and copy the following code to the .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

3. Please try on your browser

http://localhost/basicslim/public/profile/sigit

Slim Framework Simple REST API Php Example

Reference

https://www.slimframework.com/

Similarly, Slim Framework tutorial part 1 has been completed. Slim Framework usually used to build a REST API, the next time I will share how to create a simple REST API using the slim framework


Rest API And HTTP Methods (GET, POST, PUT, DELETE) Using Slim Framework And PHP

$
0
0

On this occasion I would like to share how to create, use and calling REST API on Slim Framework and PHP. This article is a continuation of my previous article “a basic introduction to slim framework“. Rest API associated with the http request method such as GET, POST, PUT and DELETE which the client will make a request to the web service.

An application usually only perform CRUD (Create, Read, Update, Delete). In the Rest API, CRUD functions in accordance with the 4 HTTP method i.e., POST, GET, PUT, and DELETE. So we can choose the right method for REST API.

Rest API And HTTP Methods (GET, POST, PUT, DELETE) Using Slim Framework And PHP

In this article I will make a simple rest API to retrieve the data in JSON format. The application will perform the request against the rest api service that was created using the Slim Framework and accessed via the PHP CURL.

In order to Service Rest API is good and easy to understand, the Developer must specify the raw data format and consistent. So a client with easy access and study the API we will create. For example this tutorial, any request will return the JSON format is as shown below

Json Format Response Simple Rest Api Using Slim Framework

In this example, the API request on PHP using CURL functions. PHP provides functions to perform the curl request using DELETE and PUT method.

Here is a simple program to make the register form, login form, edit form, delete form and index page that applications will apply the http method ( GET, POST, PUT, and DELETE) using PHP CURL to perform a simple REST API request using Slim Framework.

Simple Rest Api Using Slim Framework and Curl PHP

1. Create a project folder with name “restapi
2. Install the slim framework using the composer with the following script:

composer require slim/slim “^3.0”

3. Make sure your folder structure as shown below

Restapi Folder Project

4. Create 6 pieces PHP files in the folder example

  • login.php
  • delete.php
  • index.php
  • edit.php
  • register.php
  • logout.php

Folder “example” used to call the REST API service

login.php

<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
</head>
<body>
	
<h3>Simple example how to create rest api and use http method with slim framework by seegatesite.com</h3>


<h2>GET METHOD</h2>


<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>
" >
		
<table>
			
<tr>
				
<td>Email :</td>


<td><input type="email" name="email"></td>

			</tr>


<tr>
				
<td>Password :</td>


<td><input type="password" name="password"></td>

			</tr>


<tr>
				
<td><input type="submit" name="submit" value="login"></td>

			</tr>

		</table>

	</form>



A new user ? <a href="register.php">register</a>

	<?php  
	if(isset($_POST['submit']))
	{
		if (!empty($_POST['email']) and !empty($_POST['password'])) 
		{
			$email = $_POST['email'];
			$password = $_POST['password'];
			$ch = curl_init('http://localhost/restapi/api/get/login/'.$email.'/'.$password);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$response = curl_exec($ch);
			curl_close($ch);
			$data	= json_decode($response,true);
			if($data['data']['islogin'] == true)
			{
				$_SESSION['email'] = $data['data']['email'];
				$_SESSION['password'] = $data['data']['password'];
				$_SESSION['name'] = $data['data']['name'];
				$_SESSION['country'] = $data['data']['country'];
				header("location:index.php");
			}else
			{
				echo '
<hr />

'.$data['message'];
			}
		}else
		{
			echo 'Please fill the Email or Password ';
		}
	}
	?>
</body>
</html>

Description :

The login page will implement PHP curl to make requests with the GET method.

register.php

<!DOCTYPE html>
<html>
<head>
	<title>Register Page</title>
</head>
<body>
	
<h3>Menu Register</h3>


<h2>POST METHOD</h2>


<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>
" >
		
<table>
			
<tr>
				
<td>Email :</td>


<td><input type="email" name="email"></td>

			</tr>


<tr>
				
<td>Password :</td>


<td><input type="password" name="password"></td>

			</tr>


<tr>
				
<td>Name :</td>


<td><input type="text" name="name"></td>

			</tr>


<tr>
				
<td>Country :</td>


<td><input type="text" name="country"></td>

			</tr>


<tr>
				
<td><input type="submit" name="submit" value="Register"></td>

			</tr>

		</table>

	</form>



You need login? <a href="login.php">Login page</a>

	<?php if(isset($_POST['submit'])) { if (!empty($_POST['email']) and !empty($_POST['password']) and !empty($_POST['name']) and !empty($_POST['country'])) { $email = $_POST['email']; $password = $_POST['password']; $name = $_POST['name']; $country = $_POST['country']; $post = array( 'email' => $email,
				'password' => $password,
				'name' => $name,
				'country' => $country,
				);

			$data = json_encode($post);

			$ch = curl_init('http://localhost/restapi/api/post/register');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			$response = curl_exec($ch);
			curl_close($ch);
			$data	= json_decode($response,true);

			echo '
<hr />

'.$data['message'];
			
		}else
		{
			echo 'Please fill Data ';
		}
	}
	?>
</body>
</html>

Description :

The register page will implement PHP curl to make requests with the POST method.

index.php

<?php session_start(); if(!isset($_SESSION['email'])) { header("location:login.php"); } ?>
<!DOCTYPE html>
<html>
<head>
	<title>Welcome home </title>
</head>
<body>
	Welcome to Home <a href="logout.php">Logout</a>
	
<hr>


<table>
		
<tr>
			
<td>
				Name :
			</td>


<td>
				<?php echo $_SESSION['name']; ?>
			</td>

		</tr>


<tr>
			
<td>
				Email :
			</td>


<td>
				<?php echo $_SESSION['email']; ?>
			</td>

		</tr>


<tr>
			
<td>
				country :
			</td>


<td>
				<?php echo $_SESSION['country']; ?>
			</td>

		</tr>


<tr>
			
<td>
				<a href="edit.php">Edit</a> <a href="delete.php">Delete</a>
			</td>

		</tr>

	</table>

</body>
</html>

edit.php

<?php session_start(); if(!isset($_SESSION['email'])) { header("location:login.php"); } ?>
<!DOCTYPE html>
<html>
<head>
	<title>Edit Page</title>
</head>
<body>
	<?php if(isset($_POST['submit'])) { if ( !empty($_POST['password']) and !empty($_POST['name']) and !empty($_POST['country'])) { $email = $_POST['email']; $password = $_POST['password']; $name = $_POST['name']; $country = $_POST['country']; $post = array( 'password' => $password,
				'name' => $name,
				'country' => $country,
				);

			$data = json_encode($post);

			$ch = curl_init('http://localhost/restapi/api/put/edit/'.$email);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

			$response = curl_exec($ch);
			curl_close($ch);
			$data	= json_decode($response,true);
			echo '
<hr />

'.$data['message'];
			$_SESSION['email'] = $data['data']['email'];
			$_SESSION['password'] = $data['data']['password'];
			$_SESSION['name'] = $data['data']['name'];
			$_SESSION['country'] = $data['data']['country'];
			echo '<hr/><a href="index.php">Back to dashboard</a>';
			
		}else
		{
			echo 'Please fill Data ';
		}
	}
	?>
	
<h1>PUT METHOD</h1>


<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>
" >
		
<table>
			
<tr>
				
<td>Email :</td>


<td><input type="email" readonly value="<?php echo $_SESSION['email'] ?>" name="email"></td>

			</tr>


<tr>
				
<td>Password :</td>


<td><input type="password" value="<?php echo $_SESSION['password'] ?>" name="password"></td>

			</tr>


<tr>
				
<td>Name :</td>


<td><input type="text" value="<?php echo $_SESSION['name'] ?>" name="name"></td>

			</tr>


<tr>
				
<td>Country :</td>


<td><input type="text" value="<?php echo $_SESSION['country'] ?>" name="country"></td>

			</tr>


<tr>
				
<td><input type="submit" name="submit" value="Edit"></td>

			</tr>

		</table>

	</form>


</body>
</html>

Description :

The edit page will implement PHP curl to make requests with the PUT method.

delete.php

<?php session_start(); if(!isset($_SESSION['email'])) { header("location:login.php"); } ?>
<!DOCTYPE html>
<html>
<head>
	<title>delete Page</title>
</head>
<body>
	
<h1>DELETE METHOD</h1>


<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>
" >
		
<table>
			
<tr>
				
<td>Email :</td>


<td><input type="email" readonly value="<?php echo $_SESSION['email'] ?>" name="email"></td>

			</tr>


<tr>
				
<td>Password :</td>


<td><input type="password" value="<?php echo $_SESSION['password'] ?>" name="password"></td>

			</tr>


<tr>
				
<td>Name :</td>


<td><input type="text" value="<?php echo $_SESSION['name'] ?>" name="name"></td>

			</tr>


<tr>
				
<td>Country :</td>


<td><input type="text" value="<?php echo $_SESSION['country'] ?>" name="country"></td>

			</tr>


<tr>
				
<td><input type="submit" name="submit" value="Delete this account ?"></td>

			</tr>

		</table>

	</form>

	<?php if(isset($_POST['submit'])) { $email = $_SESSION['email']; $ch = curl_init('http://localhost/restapi/api/delete'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response,true); print_r($data); if($data['status'] == 200) { header("location:logout.php"); }else{ // echo 'error : '.json_decode($response); } } ?>
</body>
</html>

Description :

The delete page will implement PHP curl to make requests with the DELETE method.

logout.php

<?php session_start(); unset($_SESSION['email']); unset($_SESSION['password']); unset($_SESSION['name']); unset($_SESSION['country']); header("location:login.php"); ?>

5. If all of the above files is completed, the next step we will make the simple REST API code in the “api” folder. Add 2 pieces of files index.php and .htaccess in the “api” folder and copy the following code

index.php

<?php require '../vendor/autoload.php'; $c['notFoundHandler'] = function ($c) { return function ($request, $response) use ($c) { $array = array('Status'=>'404','Message'=>'Page not found');
		return $c['response']
		->withStatus(404)
		->withHeader("Content-Type","application/json")
		->write(json_encode($array));
	};
};
$app = new \Slim\App($c);

$app->delete('/delete', function($request, $response,$args) {
	if(file_exists('data.json'))
	{
		unlink("data.json");		
	}

	$array['status'] = '200';
	$array['message'] = 'delete success';
	$array['data'] = array("islogin"=>false);
	return $response->withStatus(200)
	->withHeader("Content-Type","application/json")
	->write(json_encode($array));
});

$app->get('/get/login/{email}/{password}', function($request, $response,$args) {
	$email = $args['email'];
	$password =$args['password'];
	if(file_exists('data.json'))
	{
		$datajson = json_decode(file_get_contents('data.json'), true);	
		foreach ($datajson as $key) 
		{
			$data['email'] = $key['email'];
			$data['password'] = $key['password'];
			$data['name'] = $key['name'];
			$data['country'] = $key['country'];
		}
		
	}else
	{
		$data['email'] = '';
		$data['password'] = '';
		$data['name'] = '';
		$data['country'] = '';	
	}
	
	if($email == $data['email'] and $password == $data['password'])
	{
		$array['status'] = '200';
		$array['message'] = 'login success';
		$array['data'] = array("islogin"=>true,
			"name"=>$data['name'],
			"country"=>$data['country'],
			"email"=>$data['email'],
			"password"=>$data['password']);
	}else
	{
		$array['status'] = '401';
		$array['message'] = 'Unauthorized User';
		$array['data']= array("islogin"=>false,"name"=>$data['email'],"country"=>'');

	}
	
	
	return $response->withStatus(200)
	->withHeader("Content-Type","application/json")
	->write(json_encode($array));
});

$app->post('/post/register', function($request, $response){
	$datajson = array();
	$data = json_decode($request->getBody(),true);
	$datajson[] = $data;
	$fp = fopen('data.json', 'w');
	fwrite($fp, json_encode($datajson));
	fclose($fp);

	$array['status'] = '200';
	$array['message'] = 'register success';
	$array['data']= array("islogin"=>false);
	return $response->withStatus(200)
	->withHeader("Content-Type","application/json")
	->write(json_encode($array));
});

$app->put('/put/edit/{email}', function($request, $response,$args){

	$email = $args['email'];
	$datajson = array();
	$data = json_decode($request->getBody(),true);
	$data['email'] = $email;
	$datajson[] = $data;
	$fp = fopen('data.json', 'w');
	fwrite($fp, json_encode($datajson));
	fclose($fp);

	$array['status'] = '200';
	$array['message'] = 'Edit Success';
	$array['data'] = array("islogin"=>true,
		"name"=>$data['name'],
		"country"=>$data['country'],
		"email"=>$data['email'],
		"password"=>$data['password']);
	return $response->withStatus(200)
	->withHeader("Content-Type","application/json")
	->write(json_encode($array));
});
$app->run();

Description:

To answer the request in a json format on Slim Framework using the following functions:

return $response->withStatus(200)
	->withHeader("Content-Type","application/json")
	->write(json_encode($array));

Create a handler if request is not found(404) in slim framework 3.0 using the following functions:

$c['notFoundHandler'] = function ($c) {
	return function ($request, $response) use ($c) {
		$array = array('Status'=>'404','Message'=>'Page not found');
		return $c['response']
		->withStatus(404)
		->withHeader("Content-Type","application/json")
		->write(json_encode($array));
	};
};

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Description :
The above script is used to create pretty links

Save and finish, the result will be as shown below

Simple Example How To Create Rest Api And Use Http Method With Slim Framework By Seegatesite.com

Thus my tutorial, please download the complete script on the links below to direct to practice, because I’m not good in explaining 🙂

Download project : http://wp.me/a65Dpx-H9

How To Access Fingerprint Data With PHP Without Web Services Using Zkemkeeper.dll

$
0
0

Solutions that PHP can access the fingerprint machine that does not have web services is to use zkemkeeper.dll. When the company I worked buy many fingerprint machine and it turns out that machine does not have web services, we difficult to process the data. And when I contacted the vendor, they mention that the fingerprint machine with series that we bought is not supported by web services. What’s the solution?

If your fingerprint machine, using zkemkeeper.dll as a module to process the data. PHP provides a class to be able to access the DLL file. But the DLL file can only be run on the Windows operating system. While our company system using Ubuntu Linux server. Like it or not we have to install the Windows operating system (my experiment using Windows 7 64bit) on ubuntu server using VirtualBox.

PHP can access the DLL file with the following functions

$obj = new COM("zkemkeeper.ZKEM");

Okay, here’s the tutorial on how to access the machine fingerprint using PHP and Zkemkeeper.dll

  1. Make sure you have a windows operating system (windows 7 64 bit that I use).
  2. Download the entire DLL file fingerprint (zkemkeeper.dll, etc. ..) here.
  3. Copy the entire file in the folder c:/windows/SysWOW64/.
  4. Open CMD as administrator and run the following script:
    c: cd Windows/SysWOW64 regsvr32 zkemkeeper.dll
    

    Run Cmd As Administrator

    Register The Zkemkeeper In Syswow64 Folder

    Make sure the DLL file was successfully registered on the system

    Successfully Register Zkemkeeper Dll In Syswow64 Using Regsvr32

  5. On windows, I use XAMPP server (xampp-win32-5.5.35-0-VC11-installer) to run PHP.
  6. Change settings in the php.ini, change the following settings.
     ..................... max_execution_time = 300 ..................... extension = php_com_dotnet.dll ..................... 
  7. Restart your PC.
  8. Create a PHP file and copy the followingcode:
     <?php $obj = new COM("zkemkeeper.ZKEM"); $isconnect=$obj->Connect_Net("192.168.1.199",4370); // change with your fingerprint IP ADDRESS and PORT var_dump($isconnect); 

    don’t forget to change your fingerprint IP ADDRESS AND PORT

I do not share how to process data such as taking a log, list the user, taking fingerprint templates, etc .. because the script that we make are used commercially. Bit instructions for accessing functions in zkemkeeper.dll

<?php
$zk = new COM("zkemkeeper.zkem");
echo "



<pre>";
com_print_typeinfo($zk);
echo "</pre>

";
?>

Run the script above you’ll get a set of functions in zkemkeeper.dll.

Zkemkeeper Function Script

If you use a fingerprint machine brand solution, this method works well on machines with series X100, X103, X105 and zkteco fingerprint machine. Happy coding 🙂

Thus my article on How To Access Fingerprint Data With PHP Without Web Services Using Zkemkeeper.dll may be useful.

iziMODAL – The Most Beautiful And Cool Modal Dialog Form JQuery Plugin

$
0
0

iziMODAL Plugin is an alternative jQuery modal dialog that is flexible, responsive, easy to use and very cool. If you are accustomed to using modal dialog belonging to bootstrap and bored with the look of the standard bootstrap should try this modal dialog plugin. When I met this modal dialog, the first impression I had was “OMG it’s so amazing”. Let’s see the following review

Izimodal Jquery Plugin

iziMODAL is a very lightweight jquery plugin that I’ve come across.  In addition, izimodal.js include an external library from CDNJS. iziModal is present in multiple views, we can select the appropriate type of capital that we need. Even you can make elegant notification box and has a nice animation. In addition, iziModal provides a callback function if the user close the modal dialog or click on specific element

Alert Example Izimodal

Some DEMO examples can be found on the iziModal official site. All elements are supported by CSS3 and Jquery so iziModal has a design that is elegant and impressive animations. In addition, documentation iziModal complete enough to be learned.

According to the official website, the iziModal function() has more than 40 diverse options that you can customize to your needs. We can create a custom event that we can trigger when open / close the modal dialog.

Custom Modal Dialog Izimodal

If you are a programmer once web designer. This plugin required use to enhance the look of your website. Additionally, this plugin is open source / free for download

To get this plugin, please download via the official website or you can download it from GITHUB or NPM.

Using “str_replace PHP” In MySQL With REPLACE Function

$
0
0

If you have large amounts of data in MySQL and want to change some values/characters in a particular field, it would be very inconvenient If you must be changed manually. There is MySQL function similar to str_replace in PHP that has a function to change the certain word with other words massively.

MYSQL REPLACE

MySQL REPLACE() replaces all the occurrences of a substring within a string. Perhaps we rarely use this function, but in certain situations, this function will be the savior of developers in data processing.

Using Str Replace PHP In MySQL With REPLACE Function

For example, a colleague of mine who has purchased the azoncastv2 theme. He had the data product with a very large number. Turns out he incorrectly entered the Amazon affiliate ID and asked me how to modify amazon affiliate ID in the table post massively?

By running the following query, we can change the string in the WordPress posts table massively

UPDATE wp_postmeta
SET meta_value = REPLACE(meta_value, 'your-old-tag-id', 'your-new-tag-id)
WHERE meta_value LIKE '%your-old-tag-id%'

and this one

UPDATE wp_posts
SET post_content = REPLACE(post_content, 'your-old-tag-id', 'your-new-tag-id')
WHERE post_content LIKE '%your-old-tag-id%'

This simple query can be used to change a word in a set of strings rapidly. Thus my brief tutorial on the use REPLACE in MySQL to change a specific string in a set of strings.

A Short Query To Get Details And Total Value With “ROLLUP” in MySQL

$
0
0

Searching for a total value of MySQL table fields based on a particular group can use “WITH ROLLUP” feature in MySQL. Usually, a programmer to display the details and the total value of the MySQL data used 2 times query. That is, with the “select * from table where condition …” query to look for details and “select sum (field) from table where condition …” query to find the total value. With “WITH ROLLUP” MySQL Feature we can shorten and ease a query on the database.

For example, we have a sales table as follows:
Mysql Table Receipt Seegatesite.com

And we want to display the data as shown below:

Receipt Table With Looping Mysql Query

We usually do is the following:

Show Table Data With Php And Mysql Seegatesite

With “WITH ROLLUP” feature in MySQL we can display the data along with the total price as shown below:

Rollup Function Mysql

The above results more similar to the report that had almost finished. I just run the following query to get results:

SELECT a.*,SUM(price) AS totalPrice 
FROM Receipt a 
GROUP BY receipt_code,autoinc
WITH ROLLUP

“WITH ROLLUP” MySQL Feature

MySQL has a feature WITH ROLLUP. This feature can put the data per-group. So the system can insert a row its per-group on results. And how easy is to add “WITH ROLLUP” at the end of the GROUP BY syntax.

Actually, using the plain-SQL can make the results as above, but the query is quite long and a little difficult as the following example

SELECT t.autoinc,t.receipt_code,t.product_name,t.price,t.totalPrice
FROM (
	SELECT 
		g1.*,g1.price AS totalPrice,COUNT(*) AS rec
	FROM receipt g1
	GROUP BY g1.`receipt_code`,g1.`autoinc`
	UNION ALL
		SELECT NULL AS autoinc,
			MAX(g2.receipt_code) AS receiptCode,
			g2.product_name,
			NULL AS price,
			SUM(g2.price) AS totalPrice,
			COUNT(*) AS rec
		FROM receipt g2
		GROUP BY g2.receipt_code
		UNION ALL
			SELECT 
				NULL AS autoinc,
				MAX(g3.receipt_code) AS receiptCode,
				g3.product_name,
				NULL AS price,
				SUM(g3.price) AS totalPrice,
				COUNT(*) AS rec
			FROM
				receipt AS g3
) AS t
ORDER BY 
	receipt_code,rec

Thus short tutorial on “WITH ROLLUP” MySQL Feature to get for detail and the total value of a field, may be useful 🙂

Handling Javascript Keyboard Events With JQuery Hotkeys Plugin

$
0
0

The use of keyboard shortcuts in web applications are often needed by the user. Javascript can handle keyboard event functions, so developers can use it well. On jQuery, a plugin named hotkeys.js can easily add a handler for the keyboard events with a lot of combinations.

Supported by technology and hardware that is getting better, the use of jquery will not burden the system browser in client side again. The use of jQuery hotkeys plugin will save your time in create the keyboard events in javascript.

If without the plugin, the use of keyboard codes javascript like the following example:

var isCtrl = false;
document.onkeyup=function(e){
    if(e.which == 17) 
    {
        isCtrl=false;
    }
}

document.onkeydown=function(e){
    if(e.which == 17) isCtrl=true;
    if(e.which == 83 &amp;&amp; isCtrl == true) 
    {
         alert('test 1 2 3 4 5 6 .....');
         return false;
    }
}

Please try by pressing “ctrl+s” on a web page browser, what happens?
Without jQuery plugin, you can run the javascript hotkeys. But you have to know the keyboard codes reference, below the following list of keycode in javascript

Keyboard Shortcut And Keycode Javascript Reference

Of course using Hotkeys jquery plugins will be faster in writing code.

JQuery Hotkeys Plugin

According to the official website of jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.

The use of this plugin is quite simple:

$('input.foo').bind('keydown', 'F9', function(){
  alert("this is F9");
});

But I am a little having problems when using ctrl + s on hotkeys plugin. When the input field get focus, keyboard event ctrl + s can not be run properly. Maybe I’m not good to applying them. So using javascript to handle this problem in the following ways

$(document).keydown(function(event) {
        if((event.ctrlKey || event.metaKey) &amp;&amp; event.which == 83) {
           alert("hello this is ctrl+s trigger");
            event.preventDefault();
            return false;
        };
    }
);

Maybe anyone can help me?

If you would like to see an example of the use of hotkeys plugin in full please visit JQuery hotkeys example.

There are some important things to note about how to implement a keyboard event handler in the web application.

  1. Avoid defining keyboard shortcut that has been provided by the browser, for example Ctrl + P to print.
  2. Use keywords that are rarely used as F1 – F9.
  3. Use the keyboard event handler wisely ,please do not confuse the user

Thus my article about Handling Javascript Keyboard Events With JQuery Hotkeys Plugin, hope useful.

Overhang.js A Simple And Cool Dropdown Notification Bar Messages

$
0
0

If you bored with javascript standard notification, you can try overhang.js. A lightweight notification plugin and does not interfere with the appearance of your website or application. What does the overhang.js is it?

Overhang.js will display a notification bar that dropdown from the top of the screen. This plugin works using CSS and jquery animation. Also, the overhang.js display does not interfere with the performance of your application.

Overhang Js Lightweight Dropdown Notification Bar

With the motto “A Jquery plugin to display sleek, instant notifications, confirmations or prompts inside a given element.” overhang.js can be customized according to the desire of app’s developer. In addition to displaying the notification bar, this plugin can perform prompt alerts, Confirmation Alert and also execute the callback function()

You can customize the message as adding a duration of time appears, adding close buttons, change the color of the notification message bar.

Overhang.js Demo Prompt Alert

Notification bar can display a success message, warning, error as the default option. Alert messages can be added the Yes/No button to ask the website visitors. This plugin run on all browsers that support Jquery

The use of overhang.js quite easily like the following example:

$("body").overhang({
  type: "success",
  message: "hello seegatesite"
});

This plugin was developed by Paul Krishnamurthy. A software developer who lives in Canada, please visit the official website https://paulkr.com/. To download the overhang.js plugin, you can visit the official website at http://paulkr.github.io/overhang.js/

Thus my article about Overhang.js A Simple And Cool Dropdown Notification Bar Messages, hope useful


Change Bootstrap Modal Dialog Effect With Animate.css

$
0
0

Changing a bootstrap modal dialog effect is very easy to do with animate.css. If you are bored with the standard bootstrap effect, animate.css is the best and lightweight solution to be applied with your web application.

Animate.css is an animated CSS owned by Daniel Eden that can be combined with bootstrap framework without reducing performance.

So that animation can work well you need to add the following CSS code:

.modal.fade .modal-dialog {
 -webkit-transform: translate(0);
 -moz-transform: translate(0);
 transform: translate(0);
 }
Change Bootstrap Modal Dialog Effect With Animate.css
Bootstrap Modal Window With Animation Example

To change the standard animation from bootstrap modal form, it is necessary to add a javascript modal event. As an example, I will add animation flipInX when modal dialog called and will add animation flipOutY when the modal dialog is closed.

  $('.modal').on('show.bs.modal', function (e) {
  	$('.modal .modal-dialog').attr('class', 'modal-dialog  flipInX  animated');
  })
  $('.modal').on('hide.bs.modal', function (e) {
  	$('.modal .modal-dialog').attr('class', 'modal-dialog  flipOutX  animated');
  })

Jquery script above will change the value of class attributes in the .modal and .modal-dialog class. Whereas bootstrap dialog event executed is show.bs.modal and hide.bs.modal.

Bootstrap Modals Dialog Event

Bootstrap modal dialog has a few events that can be executed when a modal dialog invoked or closed. For more details, please visit http://getbootstrap.com/javascript/#modals-events

The tutorial is completed, it is very easy to change the animation or effects on the bootstrap modal dialog.

Thus my article about Change Bootstrap Modal Dialog Effect With Animate.css, hopefully useful 🙂

[Share] My Experience Domain Transfer From The Old Registrar To Namecheap Hosting

$
0
0

Not long ago I did a domain transfer from the old registrar to Namecheap hosting. I would like to share some experiences domain transfer from the old registrar to Namecheap hosting. My judgment against Namecheap is very satisfied. Differences domain and hosting location makes me hassle to manage it. My choice to move the domains and hosting into one management falls on Namecheap.com because of a live chat support is very friendly and good service (24 hours nonstop). Just 2 days the domain transfer process has been completed. Check out reviews of transfer domain  mechanism from my old registrar to Namecheap.com.

Domain transfer process from the old registrar to Namecheap.com

Transfer Domain Name Migrate Domains To Namecheap Tips

1. Before doing a domain transfer transactions, make sure you have prepared the following conditions.

  • The domain must have been registered or transferred at least 60 days ago.
  • The domain is not in the locked status for the transfer process. If locked, please contact your old registrar support ticket to unlock it.
  • Domain not being protected by whois guard. If using the whois guard services please contact your old registrar support ticket to open it.
  • The domain must show a valid and accessible Admin email address in Whois, as the Transfer Approval email will be sent there.
  • Make sure you get the EPP code from your old domain registrar. (Code EPP stands for Extensible Provisioning Protocol. Which means that a security code to transfer the domain name. Without this code you can not transfer the domain to another registrar.)

How To Get Domain Epp Code To Transfer Domain

2. If all the above conditions you have prepared, the next step is to perform a domain transfer transaction. Please visit Namecheap domain transfer page.
Transfer Domain Transaction In Namecheap
Order Note Transfer Domain Namecheap
3. You will get an email confirmation request transfer domain to Namecheap as shown below:
Transfer Domain Request Confirmation Tutorial Transfer Domain To Namecheap4. After you approve the domain transfer request to Namecheap, you will get a confirmation email from the old registrar i.e. the domain transfer confirmation email to the new registrar.
Email Confirmation Transfer Domain From Old Registar To Namecheap HostingImmediately headed to the confirmation page and select agree to perform the domain transfer process.

5. Finally, the domain transfer process is completed in 2 days and you will get a confirmation email as shown below.
Transfer Domain From Old Registrar To Namecheap Hosting Complete In 2 Days

A little advice in order to finish quickly the domain transfer process.

Do not hesitate to contact both sides live chat support to accelerate the domain transfer process. Make sure your communication with the two sides registrar goes well

Namecheap.com

My successes can not be separated from the help of Namecheap live chat support. I sure do not hesitate to move your domain to Namecheap. Hopefully, my experience to Namecheap domain transfer can help you.

[Share My Old Stuff] Tutorial Create XML Sitemap Generator From Lists Of Keywords

$
0
0

I want to share my old stuff tool to create a sitemap XML file. Maybe there are some people who need these tools to improve their website index. Let’s follow the following tutorial

Of course, you already know what it is XML sitemap.

A sitemap is a list of pages and posts a website that can be accessed by visitors of the website/blog. Although not significantly affect the visitors, but the sitemap is extremely influential in our efforts to optimize our SEO blog. XML Sitemap in a blog will tell the search engines such as Google, Yahoo, etc. to index the list in search engines.

How To Create Xml Sitemap Generator From Lists Of Keyword With Php

If you have a website that is in the build without a CMS such as WordPress, of course, have to create your own plugin that will generate a sitemap XML file. And for a handful of people is very useful tool to add a new index to the search engine. Straight to the point follow these steps.

Tutorial how to create XML sitemap generator from a collection of keywords

1. Create a project folder with the name “sitemap”

2. Create an index.php file and copy the following code:

<?php header('Content-Type: text/html; charset=utf-8'); ?>
<html>
<head>
	<title>XML Sitemap Generator</title>
</head>
<body>

<h2>How to create xml sitemap file from keyword lists</h2>


<form method="post" action="file.php" target="_blank">

<table>
			
<tr>
				
<td>Url</td>


<td>: 
					<input type="text" name="url" size="80">
				</td>

			</tr>


<tr>
				
<td>Priority</td>


<td>: 
					<input type="text" value="0.8" name="priority">
				</td>

			</tr>


<tr>
				
<td>Change Frequently</td>


<td>: 
					<select name="changefreq">
<option value="always">always</option>
<option value="hourly">hourly</option>
<option value="daily" selected>daily</option>
<option value="weekly">weekly</option>
<option value="monthly">monthly</option>
<option value="yearly">yearly</option>
<option value="never">never</option>
					</select>
				</td>

			</tr>


<tr>
				
<td>Keyword</td>


<td>: <textarea name="keyword" cols=50 rows=30></textarea></td>

			</tr>


<tr>
<td colspan=2><button type="submit" name="submit">Submit</button></td>
</tr>

		</table>

	</form>

</body>
</html>

3. Create file.php file and copy the following code:

<?php function text_to_strip($text) { return str_replace(" ", "-", seotext($text)); } function seotext($str) { $str = str_replace("(", "", $str); $str = str_replace(")", "", $str); $str = str_replace("&", "", $str); $str = str_replace(",", "", $str); $str = str_replace("]", "", $str); $str = str_replace(";", "", $str); $str = str_replace("[", "", $str); $str = str_replace("!", "", $str); $str = str_replace('"', '', $str); $str = str_replace("_", "", $str); $str = str_replace("/", "", $str); $str = str_replace("@", "", $str); $str = str_replace("$", "", $str); $str = str_replace("%", "", $str); $str = str_replace("^", "", $str); $str = str_replace("~", "", $str); $str = str_replace("*", "", $str); $str = str_replace("'", "", $str); $str = str_replace("|", "", $str); $str = str_replace("+", "", $str); $str = str_replace(":", "", $str); $str = str_replace("?", "", $str); $str = str_replace("#", "", $str); $str = str_replace(".", "", $str); $str = str_replace("}", "", $str); $str = str_replace("{", "", $str); $variable = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u,é"); $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u,e"); $i=0; foreach ($variable as $key=> $value) {
			$str = str_replace($value, $replace[$i], $str);
			$i++;
		}
		
		$str = implode('-',array_filter(explode('-',$str)));
		return strtolower($str);
	}
	if($_POST['keyword']<>'' or $_POST['priority']<>'' or $_POST['url']<>'' or $_POST['changefreq']<>'')
	{
		$text = explode("\n", $_POST['keyword']);
		$content = '<?xml version="1.0" encoding="UTF-8"?>
		<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
		foreach ($text as $key => $value) {
			$content .='<url>';
			$content .='<loc>'.$_POST['url'].text_to_strip($value).'</loc>';
			$content .='<lastmod>'.date("c").'</lastmod>';
			$content .='<changefreq>'.$_POST['changefreq'].'</changefreq>';
			$content .='<priority>'.$_POST['priority'].'</priority>';
			$content .='</url>';
		}
		$content .='</urlset>';
		header('Content-Description: sitemap xml');
		header('Content-type: text/xml');
		header('Content-disposition: attachment; filename=sitemap-a.xml');
		header('Content-Length: '.strlen($content));
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Expires: 0');
		header('Pragma: public');
		echo $content;
		exit;
	}else{
		echo 'All of input field can not be empty';
	}
	?>

Please run this application via localhost: http://localhost/sitemap/

Please see the following snippet of how these tool work

If already formed XML file, please upload on your hosting and register the sitemap.XML file on google and bing webmaster. To change or add a sitemap parameters, please visit the sitemap official website to add a standard sitemap protocol

Thus tutorial create a sitemap generator XML file using PHP, may be useful

Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 1

$
0
0

How to build a simple point of sale system using PHP and Jquery. This article is a series of several of my articles about CRUD. Here I will focus on making a simple point of sale with PHP, MYSQL, Jquery, PDO and ADMINLTE Framework. I will divide this article into sections where each section will implement the module from the POS.

What is the point of sale (POS)? A point of sale is also called cashier program. This program is used for information systems in stores. Some modules that exist on POS Systems such as record customer data, suppliers, sales, purchases, print sales notes, print reports and much more. By building this PHP POS program you can earn a lot of money by selling it at the shops around you.

Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 1

In this article, I will not create all modules from POS. If you want me to make a complete POS module, you have to pay me with a high-cost :p LOL.

Some of the equipment needed

1. PHP Server (XAMPP or you can install apache and PHP server in Linux)
2. PHP (Having used PDO as a MySQL connection, this application has support for PHP 7)
3. MySQL Database
4. Jquery Library
5. Admin LTE Template, download here.

Some support plugins include:

  1. Sweetalert.js plugin (Beautiful plugin alerts to replace standard javascript alerts).
  2. Hotkey.js plugin (Create a shortcut button with javascript).
  3. Redirect.js plugin (used to send POST data using javascript).
  4. Datatables bootstrap plugin (used to create responsive tables).
  5. Bootstrap notify plugin (used to display notifications).
  6. Myfunction.js, a collection of my javascript functions that will use to speed up build the application
  7. session_checker.js, my jquery script to check session every time page loaded.

You can download all supported file in the link below

supported file download link

The module will be created in this tutorial:

  1. Creating login page – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 1.
  2. Create Dynamic Menu and Dashboard Page – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 2.
  3. Create Master User Form – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 3.
  4. Create Master Item / Product Form – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 4.
  5. Creating Sales Form / Point of sale – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 5

And as a bonus article, I will include an article how to create a shopping receipt with PHP and FPDF.

As a preliminary preparation, please create a MySQL database with the name “pos“. Add 1 table named m_user. As shown below

Create Pos Database And M User Table Tutorial Build Point Of Sale With PHP PDO MySQL And Jquery

Add a new user with the following query

insert into `m_user` (`id_user`, `username`, `pass_user`, `h_menu`, `uniq_login`) values('6','ADMIN',MD5('123'),'1,2,3','');
insert into `m_user` (`id_user`, `username`, `pass_user`, `h_menu`, `uniq_login`) values('7','PEDRO',MD5('123'),'1,3','');
insert into `m_user` (`id_user`, `username`, `pass_user`, `h_menu`, `uniq_login`) values('8','VALE',MD5('123'),'1,2','');

Okay, let’s begin the tutorial

Tutorial create login page with PHP and AdminLTE Templates

1. Create a project folder with the name “pos
2. Make sure you have downloaded the adminLTE template, if not please download at the official site here
3. Extract the adminLTE template into the “pos” project folder
4. Add new folders “application“, “image” and “library” in the pos folder.
5. Add 6 new folders into “application” folder: layout, main, master, model, sales, utility.
6. Create 4 PHP files inside the “library” folder: check_access.php, check_login.php, checksession.php and config.php. Then fill the entire file with the following script:

check_access.php

<?php
require_ once("../model/dbconn.php");
require_ once("../model/pos.php");
$id_user = $_SESSION['pos_id'];
$asmenu = explode(",", $_SESSION['pos_h_menu']);
if (!in_array($idsmenu, $asmenu))
{
 require_ once("../model/dbconn.php");
 require_ once("../model/pos.php");
 $id_user = $_SESSION['pos_id'];
 $pos = new pos();
 $html = '<div style="margin:0 auto ;text-align:center;width:80%"><img src="../../image/warning.png"><h3>Restricted Access, Back to <a href="'.$sitename.'aplication/main/">Dashboard Menu</a></h3>
 </div>';
 die($html);
}
?>

Check_access.php used to check user access every time user visit the menu. If the user does not have access to a menu will be given a warning restricted access with a “warning” image like below:

Restricted Access

check_login.php

<?php
if (
	!isset($_SESSION['pos_username']) 
	or !isset($_SESSION['pos_id']) 
	or !isset($_SESSION['pos_uniqid']) 
	or  !isset($_SESSION['pos_h_menu']) )
{
	header('Location: '.$sitename.'application/main/login.php');
}
?>

check_login.php used to check user session. If the user does not have a login session, it will be redirected to the login page

checksession.php

<?php 
session_start();
include "config.php";
if (!isset($_SESSION['pos_username']) 
	or !isset($_SESSION['pos_id']) 
	or !isset($_SESSION['pos_uniqid']) 
	or  !isset($_SESSION['pos_h_menu']) )
{
	$data['result'] = '-1';
	$data['url'] = $sitename.'application/main/login.php?error=session_die';
}else{
	$data['result'] = '1';
	$data['url'] = 'access granted';
}
echo json_encode($data);
?>

checksession.php used to check user session. If the user session has been exhausted it will be redirected to the login page

config.php

<?php
date_default_timezone_set("Asia/Jakarta");
$sitename="/pos/";
?>

7. Create 5 PHP files inside the “layout” folder: bottom-footer-table.php, bottom-footer.php, footer.php, header.php, top-header.php. Then fill the entire file with the following script:

top-header.php.

<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!-- no cache headers -->
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="no-cache">
  <meta http-equiv="Expires" content="-1">
  <meta http-equiv="Cache-Control" content="no-cache">
  <!-- end no cache headers -->
  <title><?php 
  if($titlepage){
    echo $titlepage;
  }else
  {
    echo '';
  }
  ?></title>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="../../dist/font-awesome-4.5.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="../../dist/ionic/css/ionicons.min.css"> 
  <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">
  <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css">
  <link rel="stylesheet" href="../../dist/css/responsive.dataTables.min.css">
  <link rel="stylesheet" href="../../dist/css/sweetalert.css">
  <link rel="stylesheet" href="../../dist/css/custom.css">
  <link rel="shortcut icon" href="../../dist/img/favicon.ico" />

header.php

header.php

For a while we ignore header.php first, I will discuss in part 2

footer.php

</div><!--container-->
</div><!-- /.content-wrapper -->
<!-- ./main content -->
<div class="scroll-top-wrapper "><!-- back to top button-->
  <span class="scroll-top-inner">
    <i class="fa fa-2x fa-arrow-circle-up"></i>
  </span>
</div> <!-- end back to top button-->
 <footer class="main-footer"> 
 	<div class="pull-right hidden-xs">
 		<b>Version</b> 1.0 
 	</div>
 	<strong>Copyright &copy; <?php echo date('Y'); ?> <a href="#">Seegatesite.com Inc</a>.</strong> All rights reserved.
 </footer>
</div><!-- ./wrapper -->
<div id="loadbargood" class="loadbargood hidden"></div>

bottom-footer.php

<script src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="../../plugins/jQueryUI/jquery-ui.min.js"></script>
<script>
  $.widget.bridge('uibutton', $.ui.button);
</script>
<script src="../../bootstrap/js/bootstrap.min.js"></script>
<script src="../../plugins/slimScroll/jquery.slimscroll.min.js"></script>
<script src="../../plugins/fastclick/fastclick.min.js"></script>
<script src="../../plugins/input-mask/jquery.inputmask.js"></script>
<script src="../../plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="../../plugins/input-mask/jquery.inputmask.extensions.js"></script>
<script src="../../plugins/bootstrap-notify/bootstrap-notify.min.js"></script>
<script src="../../dist/js/app.min.js"></script>
<script src="../../dist/js/myfunction.js" type="text/javascript"></script>
<script src="../../dist/js/sweetalert.min.js" type="text/javascript"></script>
<script src="../../dist/js/session_checker.js" type="text/javascript"></script>
<script src="../../dist/js/hotkey.js"></script>
<script src="../../dist/js/jquery.dataTables.min.js"></script>
<script src="../../dist/js/dataTables.bootstrap.min.js"></script>
<script src="../../dist/js/dataTables.responsive.min.js"></script>

5 files are used to create an adminLTE layout. Divided into five sections to be easy to manage bootstrap adminLTE view

8. Add a warning image into “image” folder

Warning

9. Do not forget to put supporting files in the right folder

  • sweetalert.js → pos/dist/js/ folder
  • hotkey.js → pos/dist/js/ folder
  • check_session.js → pos/dist/js/ folder
  • myfunction.js → pos/dist/js/ folder
  • bootstrap-notify folder → pos/plugin/ folder
  • sweetalert.css → pos/dist/css/ folder
  • loadbargood.js → pos/dist/js/ folder

10. Create custom.css and put on the pos/dist/css/ folder. Copy the following CSS script into custom.css file

.form-horizontal .control-label {
	text-align: left;
}
.txtperiode{
	display: inline;
}

.newbox{
    font-size: 36px;
    line-height: 70px;
    text-align: right;
}
.scroll-top-wrapper {
	position: fixed;
	opacity: 0;
	visibility: hidden;
	overflow: hidden;
	text-align: center;
	z-index: 99999999;
	background-color: #777777;
	color: #eeeeee;
	width: 50px;
	height: 48px;
	line-height: 48px;
	right: 30px;
	bottom: 30px;
	padding-top: 2px;
	border-top-left-radius: 10px;
	border-top-right-radius: 10px;
	border-bottom-right-radius: 10px;
	border-bottom-left-radius: 10px;
	-webkit-transition: all 0.5s ease-in-out;
	-moz-transition: all 0.5s ease-in-out;
	-ms-transition: all 0.5s ease-in-out;
	-o-transition: all 0.5s ease-in-out;
	transition: all 0.5s ease-in-out;
}
.scroll-top-wrapper:hover {
	background-color: #888888;
}
.scroll-top-wrapper.show {
	visibility:visible;
	cursor:pointer;
	opacity: 1.0;
}
.scroll-top-wrapper i.fa {
	line-height: inherit;
}
/* end of scroll to top */
label{
	font-weight: 500;
}

@media only screen and (max-width : 480px) {
	.wraptextplease{
		width: 178px;
	}
}


.ui-autocomplete {
	position: absolute;
	top: 100%;
	left: 0;
	z-index: 1000;
	float: left;
	display: none;
	min-width: 160px;
	_width: 160px;
	padding: 4px 5px;
	margin: 2px 0 0 0;
	list-style: none;
	background-color: #ffffff;
	border-color: #ccc;
	border-color: rgba(0, 0, 0, 0.2);
	border-style: solid;
	border-width: 1px;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
	-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
	box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
	-webkit-background-clip: padding-box;
	-moz-background-clip: padding;
	background-clip: padding-box;
	*border-right-width: 2px;
	*border-bottom-width: 2px;

	.ui-menu-item > a.ui-corner-all {
		display: block;
		padding: 3px 15px;
		clear: both;
		font-weight: normal;
		line-height: 18px;
		color: #555555;
		white-space: nowrap;

		&.ui-state-hover, &.ui-state-active {
			color: red;
			text-decoration: none;
			background-color: #0088cc;
			border-radius: 0px;
			-webkit-border-radius: 0px;
			-moz-border-radius: 0px;
			background-image: none;
		}
	}
}
.ui-state-focus {
	background-color: #ff851b !important;
	color: #ffffff !important;
	padding-left: 10px;
	cursor:pointer;
}
.ui-menu-item{
	padding-top: 10px;
}
.txtcheckbox{
	width: 30px; /*Desired width*/
	height: 30px; /*Desired height*/
}
.txtcheckbox2{
	width: 20px; /*Desired width*/
	height: 20px; /*Desired height*/
}


.loadbargood {
    display:    block;
    position:   fixed;
    z-index:    99999999999999999999;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .7 ) 
                url('../img/loadbargood.gif') 
                50% 50% 
                no-repeat;
}

Make sure your folder structure like the following image

Folder Structure Pos Project Tutorial Create Point Of Sale With Php

The entire file and code in the above is a supporting file, the next step we will create the first module that is creating a login form.

Create 4 PHP file in the main folder (pos/application/main/) like the following image:

Main Folder

index.php

<h1> Dashboard Page </h1>
<h2>Under Maintenance</h2>

index.php is a dashboard page. For a while we just give the code as above, we will change in the next article

login.php

<?php include "../../library/config.php" ?>
<?php $titlepage="Login Form System"; ?>
<?php include "../layout/top-header.php"; //header template ?> 
<body class="hold-transition login-page">
  <div class="login-box">
    <div class="login-logo">
      <a href="#"><center><b>SEEGATESITE.COM</b><br/><small>EXAMPLE POINT OF SALES</small></a>
    </div><!-- /.login-logo -->
    <div class="login-box-body">
      <p class="login-box-msg">Sign in to start your session</p>
      <form action="authorization.php" method="post">
        <div class="form-group has-feedback">
          <input type="text" class="form-control" autofocus value="" name="username" id="username" placeholder="Username">
          <span class="glyphicon glyphicon-user form-control-feedback"></span>
        </div>
        <div class="form-group has-feedback">
          <input type="password" class="form-control" value="" name="password" id="password" placeholder="Password">
          <span class="glyphicon glyphicon-lock form-control-feedback"></span>
        </div>
        <div class="row">
          <div class="col-xs-8">

          </div><!-- /.col -->
          <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat">Login</button>
          </div><!-- /.col -->
        </div>
      </form>
      <br>
      <div class="information-box round">
        <div class="callout callout-danger">
          <?php
          if (!empty($_GET['error'])) 
          {
            if ($_GET['error'] == 1) 
            {
              echo 'Please fill out username or password';
            } 
            else if ($_GET['error'] == 2)
            {
              echo 'Please fill out username';
            } 
            else if ($_GET['error'] == 3)
            {
              echo 'Please fill out password';
            }
            else if ($_GET['error'] == 4)
            {
              echo 'Invalid email or password';
            } else if ($_GET['error'] == 'session_die')
            {
              echo 'Your login session is over!!, please sign in again';
            }
          }else
          {
            echo 'Please fill out your username and password to sign in';
          }
          ?>
        </div>
      </div>
    </div><!-- /.login-box-body -->
  </div><!-- /.login-box -->
  <center><p>Copyright &copy; <?php echo date("Y");?> Seegatesite.com., inc. All rights reserved</p></center>
  <script src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script>
  <script src="../../bootstrap/js/bootstrap.min.js"></script>
  <script src="../../plugins/bootstrap-notify/bootstrap-notify.min.js"></script>
  <script src="../../dist/js/myfunction.js" type="text/javascript"></script>
  <script src="../../dist/js/sweetalert.min.js" type="text/javascript"></script>
</body>
</html>

The focus on the login page is the error code when it fails to login, you can change these code with your own.

logout.php

<?php
session_start();
include "../../library/config.php";
require_ once ("../model/dbconn.php");
require_ once ("../model/pos.php");
if (!isset($_SESSION['pos_username']) or 
	!isset($_SESSION['pos_id']) or
	!isset($_SESSION['pos_h_menu']) or
	!isset($_SESSION['pos_uniqid']) )
{	
	header('Location: '.$sitename.'application/main/login.php');
}

unset($_SESSION['pos_username']);
unset($_SESSION['pos_id']);
unset($_SESSION['pos_h_menu']);
unset($_SESSION['pos_uniqid']);
unset($_SESSION['name_shop']);
unset($_SESSION['alamat_toko']);
unset($_SESSION['telp_toko']);
header('Location: '.$sitename.'application/main/login.php');
?>

authorization.php

<?php
session_start();
include "../../library/config.php";
require_ once("../model/dbconn.php"); // delete white space between require_ once
require_ once("../model/pos.php"); // delete white space between require_ once

$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) && empty($password)) {
	header('location:login.php?error=1');
	break;
} else if (empty($username)) {
	header('location:login.php?error=2');
	break;
} else if (empty($password)) {
	header('location:login.php?error=3');
	break;
}
$sv = new pos();
$data = $sv->getLogin($username,$password);
if ($data[2] == 1) 
{
	$_SESSION['pos_username'] = $username;
	$_SESSION['pos_id'] = $data[1]['id_user'];
	$_SESSION['pos_h_menu'] = $data[1]['h_menu'];
	$_SESSION['pos_uniqid'] = uniqid();
	$_SESSION['name_shop'] = $data[1]['name_shop'];
	$iduser = $_SESSION['pos_id'];
	//$sv->deleteTempSaleByUser($iduser);
	header('location:../main/index.php');
}
else
{
	header('location:login.php?error=4');
}
?>

The form on the login page will take us to the authorization page. The authorization of this page will check whether the user has access to the system. And the system will set the session to the user

The next step we will create PHP file Which is used to hold a collection of MySQL queries and SQL database connections with PDO.

Add 2 PHP file as dbconn.php and pos.php in the “model” folder (pos/application/main/)

dbconn.php

<?php
$dbuserx='root'; // change with your own database username
$dbpassx=''; // change with your own database password
class dbconn {
	public $dblocal;
	public function __construct()
	{

	}
	public function initDBO()
	{
		global $dbuserx,$dbpassx;
		try {
			$this->dblocal = new PDO("mysql:host=localhost;dbname=pos;charset=latin1",$dbuserx,$dbpassx,array(PDO::ATTR_PERSISTENT => true));
			$this->dblocal->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
		}
		catch(PDOException $e)
		{
			die("Can not connect database");
		}
		
	}
	
}
?>

dbconn.php used to save MySQL config with PDO

pos.php

<?php
class pos extends dbconn {
	public function __construct()
	{
		$this->initDBO();
	}


 /******************************************************************************
   TABEL T_JUAL AND TEMP_JUAL
 *******************************************************************************/
   public function deleteTempSaleByUser($iduser)
   {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("delete from temp_sale where id_user = :id");
      $stmt->bindParam("id",$iduser);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Success Delete!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }

  /*********************query for system*********************/
  public function getLogin($user,$pass)
  {
   $db = $this->dblocal;
   try
   {
    $stmt = $db->prepare("select a.*,
      (select name_shop from r_ref_system where id = 1) as name_shop,
      (select address_shop from r_ref_system where id = 1) as address_shop,
      (select phone_shop from r_ref_system where id = 1) as phone_shop
      from m_user a where  upper(a.username)=upper(:user) and a.pass_user=md5(:id)");
    $stmt->bindParam("user",$user);
    $stmt->bindParam("id",$pass);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = $stmt->fetch(PDO::FETCH_ASSOC);
    $stat[2] = $stmt->rowCount();
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    $stat[2] = 0;
    return $stat;
  }
}
}

?>

The creation of login page has been completed, before test, the application on the browser make sure you edit .htaccess and index.php (pos/index.php) file in the folder “pos

.htaccess

Options All -Indexes
RewriteEngine On
ErrorDocument 404 /pos/

index.php

<?php
session_start();
include "library / config.php";
if (
 !isset($_SESSION['pos_username']) 
 or !isset($_SESSION['pos_id']) 
 or !isset($_SESSION['pos_uniqid']) 
 or !isset($_SESSION['pos_h_menu']) )
{
 header('Location: '.$sitename.'application/main/login.php');

}else
{
 header('Location: '.$sitename.'application/main/index.php');
}
?>

Please test your application via browser with following address: http://localhost/pos/

Login Page

If successful login, you will be taken to the index page as shown below:

Dashboard Page

If any questions please fill in the comment form below. The complete project can be downloaded in the last article of this tutorial (Article Part 5).

The first part of the tutorial has been completed, The next section will create a dynamic menu and dashboard page on adminLTE

Dynamic Menu AdminLTE And Dashboard Page – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 2

$
0
0

After part 1 is complete the next step we will create dynamic menu and dashboard page on adminLTE.  Before I started this article, I make sure you have read Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 1 in order to follow this article well. The dashboard page will look like the following pictureTutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 1

In part 2 we will only edit the file index.php (pos/application/main/index.php), header.php (pos/application/layout/header.php) and pos.php (pos/application/model/pos.php)

I have discussed “how to create a dynamic menu on adminLTE” on some of my previous articles:

I will not discuss in more detail how to create this menu, you can read some of my articles above to understand more. To start making this menu, make sure you have created table m_user in part 1 article.

Then make 2 more tables on the MySQL database table r_menu and table r_sub_menu as follows

R Menu Table To Create Dynamic Menu Adminlte

R Sub Menu To Create Dynamic Menu Adminlte

In addition to the 2 tables above, please create a r_ref_system table to hold the main data of the application. r_ref_system table structure like the following picture:

R Ref System Table Structure How To Create Pos Php

Up to this point, we have succeeded in creating 4 tables in the pos database

4 Tables In Pos Database Mysql

Add some of the following queries to fill the table r_menu and r_submenu

insert  into 'r_menu'('id_menu','name_menu','menu_order','icon') values (1,'Master',1,'');
insert  into 'r_menu'('id_menu','name_menu','menu_order','icon') values (2,'Penjualan',2,'');
insert  into 'r_menu'('id_menu','name_menu','menu_order','icon') values (3,'Utility',7,'');

insert  into 'r_menu_sub'('id_sub_menu','name_sub_menu','id_menu','sub_menu_order','hak_akses','url','content_before','content_after','icon','title','target') values (1,'Master Item',1,2,'2','application/master/v_item.php',NULL,NULL,'<i class=\"fa  fa-arrow-right\"></i>','MASTER ITEMS','_self');
insert  into 'r_menu_sub'('id_sub_menu','name_sub_menu','id_menu','sub_menu_order','hak_akses','url','content_before','content_after','icon','title','target') values (2,'Point Of Sale',2,2,'2','application/sales/v_pos.php',NULL,NULL,'<i class=\"fa  fa-arrow-right\"></i>','POINT OF SALES','_self');
insert  into 'r_menu_sub'('id_sub_menu','name_sub_menu','id_menu','sub_menu_order','hak_akses','url','content_before','content_after','icon','title','target') values (3,'Master User',3,1,'4','application/utility/v_mstuser.php',NULL,NULL,'<i class=\"fa  fa-arrow-right\"></i>','MASTER USERS','_self');

And execute the following query to fill the table r_ref_system

insert  into 'r_ref_system'('id','name_shop','address_shop','phone_shop') values (1,'SEEGATESITE SHOP','1193 Hartway Street Rapid City, SD 57702','08777-8370-888');

Edit the header.php file (pos/application/layout/header.php) and fill in the following script:

</head>
<body class="hold-transition skin-black layout-top-nav">
  <!-- Site wrapper -->
  <div class="wrapper">
    <header class="main-header"> 
      <nav class="navbar navbar-static-top">
        <div class="container-fluid">
          <div class="navbar-header">
            <a href="<?php echo $sitename.'application/main/index.php';?>" class="navbar-brand">
             <span class="logo-mini"> 
              <b>Seegate</b>site
            </span>
          </a>
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
            <i class="fa fa-bars"></i>
          </button>
        </div>
        <!-- main navigation bar disini -->
        <div class="collapse navbar-collapse pull-left" id="navbar-collapse">
          <ul class="nav navbar-nav">
            <?php 
            $sv = new pos(); 
            $data = $sv->getMenu();
            $key = $data[1];
            ?>
            <?php 
            foreach($key as $menu) 
            {
              $idmenux=$menu['id_menu'];
              $id_menu=$menu['id_menu'];
              $query_sub_menu =  $sv->getSubMenu($id_menu);
              $jumlah_submenu = count($query_sub_menu[1]); 
              if($jumlah_submenu > 0){
                $cekmenuz=0;
                /*--------------------*/
                foreach($query_sub_menu[1] as $sub_menu)
                {  
                 $mymenu=$_SESSION['pos_h_menu'];
                 $arramymenu=explode(",", $mymenu);
                 if(in_array($sub_menu['id_sub_menu'], $arramymenu))
                 {    
                  $cekmenuz++;
                }
              } 
              /*--------------------*/


            }
            if($cekmenuz >0)
            {
              ?>
              <li class="dropdown"><a  href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo $menu['name_menu']; ?> <span class="caret"></span></a>
                <?php 
              }

              if($jumlah_submenu > 0){  ?>
              <ul class="dropdown-menu" role="menu">
               <?php
               foreach($query_sub_menu[1] as $sub_menu)
               {  
                 $mymenu=$_SESSION['pos_h_menu'];
                 $arramymenu=explode(",", $mymenu);

                 if(in_array($sub_menu['id_sub_menu'], $arramymenu))
                 {    
                  echo $sub_menu['content_before'] ;             
                  ?>
                  <li>
                    <a class="titles" href="<?php echo $sitename.$sub_menu['url']; ?>" target="<?php echo $sub_menu['target']; ?>" title="<?php echo $sub_menu['title']; ?>" >
                     <?php echo $sub_menu['icon'].$sub_menu['name_sub_menu']; ?> 
                   </a>
                 </li>
                 <?php
                 echo $sub_menu['content_after'] ; 
               }
             } 
             ?>
           </ul>
           <?php 
         } 
         ?>
       </li>
       <?php 
     } 
     ?>
   </ul>
 </div> 
 <!-- /.navbar-collapse --> 
 <!-- ./ main navigation bar -->

 <div class="navbar-custom-menu">
  <ul class="nav navbar-nav">
   <li class="dropdown user user-menu">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
      <img src="../../dist/img/avatar5.png" class="user-image" alt="User Image">
      <span class="hidden-xs"><?php echo $_SESSION['pos_username']; ?></span>
    </a> 
    <ul class="dropdown-menu"> 
      <!-- User image -->
      <li class="user-header">
        <img src="../../dist/img/avatar5.png" class="img-circle" alt="User Image">
        <p>
          <?php echo $_SESSION['pos_username']; ?>
        </p>
      </li>              
      <!-- Menu Footer-->
      <li class="user-footer">
        <div class="pull-left">
          <a href="<?php echo $sitename.'application/utility/v_ubah_password.php'; ?>" title="Change Password " class="btn btn-default btn-flat">Change Password</a>
        </div>
        <div class="pull-right">
        <a href="<?php echo $sitename.'application/main/logout.php'; ?>" title="Close Application" class="btn btn-default btn-flat">Logout</a>
        </div>
      </li>
    </ul>
  </li>
  <li>
    <a class="titles" href="<?php echo $sitename.'application/main/logout.php'; ?>" ><i class="titles fa fa-sign-out" title="Close Application"  ></i></a>
  </li>
</ul>
</div><!--  /.<div class="navbar-custom-menu">-->
</div><!-- ./container -->
</nav>
</header>

<!-- main content -->
<div class="content-wrapper">
  <div class="container-fluid">

Edit the index.php file (pos/application/main/index.php) and fill in the following script:

<?php include "../../library/config.php"; ?>
<?php $titlepage="Dashboard"; ?>
<?php
require_ once("../model/dbconn.php");
require_ once("../model/pos.php");
include "../layout /top-header.php"; 
include "../../library /check_login.php";

include "../layout/header.php"; 
?>
<section style="margin-bottom:10px;" class="content-header">
	<h1>
		Dashboard
		<small>Page</small>
	</h1>
</section>
<section class="content-main">
	<div class="row">
		<div class="col-xs-12">
			<div class="box box-solid box-danger">
				<?php
				$pos = new pos();
				$toko = $pos->getrefsytem();
				$nameshop = $toko[1]['name_shop'];
				$address_shop = $toko[1]['address_shop'];
				$phoneshop = $toko[1]['phone_shop'];
				?>
				<div class="box-header">
					<h1 class="box-title"><?php echo $nameshop;?></h1>
				</div> <!-- end of box-header -->
				<div class="box-body">
					<h4><?php echo $address_shop;?></h4>
					<h5>Telp : <?php echo $phoneshop;?></h5>
				</div> <!-- end of box-body -->
			</div><!-- end of box box-solid bg-light-blue-gradiaent -->
		</div>
	</div><!-- row -->
	<div class="row">
		<div class="col-md-9">
			<div class="box box-info">
				<div class="box box-info">
					<div class="box-header">
						<h3 class="box-title">Search Item</h3>
					</div> <!-- end of box-header -->

					<div class="row">
						<div class=" col-xs-12" style="padding-left:25px;padding-right:25px">
							<input type="text" class="form-control " id="txtsearchitem" placeholder="Search item or item id here...">
						</div>
					</div>				
					<div class="box-body">
						<div class="box-body table-responsive no-padding" style="max-width:900px;">
							<table id="table_search" class="table  table-bordered table-hover table-striped">
								<thead>
									<tr class="tableheader">
										<th style="width:40px">#</th>
										<th style="width:60px">Id</th>
										<th style="width:300px">Items</th>
										<th style="width:100px">Price</th>
										<th style="width:120px">Stock</th>
									</tr>
								</thead>
								<tbody></tbody>
							</table>
						</div>				
					</div> <!-- end of box-body -->

				</div>

			</div><!-- end of div box info -->
		</div><!-- end of col-md-8 -->
		<div class="col-md-3">
			<div class="small-box bg-green">
				<div class="inner">
					<h3>30</h3>
					<p>Today Sales</p>
				</div>
				<div class="icon">
					<i class="ion ion-stats-bars"></i>
				</div>
				<a href="#" id="lapjuals" class="small-box-footer"> More Detail <i class="fa fa-arrow-circle-right"></i></a>
			</div><!-- end of small-box-green -->

			<div class="small-box bg-aqua">
				<div class="inner">
					<h3>10</h3>
					<p>Out of stock items</p>
				</div>
				<div class="icon">
					<i class="ion ion-bag"></i>
				</div>
				<a href="<?php echo $sitename;?>application/mutasi/l_barang_abis.php" target="_blank" class="small-box-footer">Info detail <i class="fa fa-arrow-circle-right"></i></a>

			</div><!-- end of col md 4 -->
		</div><!-- end of row -->
	</section>
	<?php include "../layout/footer.php"; //footer template ?> 
	<?php include "../layout/bottom-footer.php"; //footer template ?> 
	<script src="../../dist/js/redirect.js"></script>
	<script>
		$(document).on("keyup keydown","#txtsearchitem",function(){
			var searchitem = $("#txtsearchitem").val();
			value={
				term : searchitem,
			}
			$.ajax(
			{
				url : "../master/c_search_item.php",
				type: "POST",
				data : value,
				success: function(data, textStatus, jqXHR)
				{
					var data = jQuery.parseJSON(data);
					$("#table_search tbody").html(data.data)
				},
				error: function(jqXHR, textStatus, errorThrown)
				{
					
				}
			});
		});

	</script>
</body>
</html>

Edit the pos.php file (pos/application/model/pos.php) and add the following script:

/******************************************************************************
    START OF pos MENU CODE
 *******************************************************************************/
    public function getMenu()
    {
    	$db = $this->dblocal;
    	try
    	{
    		$stmt = $db->prepare("select * from r_menu order by menu_order");
    		$stmt->execute();
    		$stat[0] = true;
    		$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    		return $stat;
    	}
    	catch(PDOException $ex)
    	{
    		$stat[0] = false;
    		$stat[1] = $ex->getMessage();
    		return $stat;
    	}
    }

    
    public function getSubMenu($id)
    {
    	$db = $this->dblocal;
    	try
    	{
    		$stmt = $db->prepare("select * from r_menu_sub where id_menu = :id order by sub_menu_order asc");
    		$stmt->bindParam("id",$id);
    		$stmt->execute();
    		$stat[0] = true;
    		$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    		return $stat;
    	}
    	catch(PDOException $ex)
    	{
    		$stat[0] = false;
    		$stat[1] = $ex->getMessage();
    		return $stat;
    	}
    }

public function getrefsytem()
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("select a.* from r_ref_system a where id = 1 ");
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = $stmt->fetch(PDO::FETCH_ASSOC);
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      $stat[2] = 0;
      return $stat;
    }
  }

To try the dynamic menu please change the value in a h_menu field in the m_user table. Change the menu to 1,2 or 1,3 and see the result.

Dashboard Page Point Of Sale Php Adminlte

If  you need complete project from this tutorial, you can download it from tutorial part 5 here.

I think the 2nd part tutorial is pretty easy so I do not need to explain in detail. Up here Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 2 has been completed, the next article will share how to create master user page in point of sale php.

Create Form User – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 3.

$
0
0

Continuing my article Tutorial Build Point Of Sale System With PHP, PDO, MySQL And Jquery. If previously I have discussed how to create a login form and dynamic menu adminLTE. In section 3 will create a master user page, which is used to add, edit and delete user data. To start this section, you should read the previous tutorials part 1 and part 2:

Okay, let’s start the tutorial to create a master user form with PHP and adminLTE Template

Master User Page Tutorial Create Pos With Php

I’ve discussed how to create a user permission to set the user’s access menu in the article http://seegatesite.com/how-to-create-user-permissions-view-to-dynamic-sidebar-menu-adminlte/. I will discuss it again by creating a user form menu so we can better understand it.

Add 3 new files in the “utility” folder (post/application/utility): c_mstuser.php, j_mstuser.js, v_mstuser.php. Fill in the following script on each file

v_mstuser.php

<?php 
$titlepage="Master User";
$idsmenu=3;
include "../../library/config.php";
require_ once("../model/dbconn.php");
require_ once("../model/pos.php");
include "../layout/top-header.php"; 
include "../../library /check_login.php";
include "../../library /check_access.php";
include "../layout/header.php"; ?>

<section class="content">
  <div class="box box-success">
    <div class="box-header with-border">
      <h3 class="box-title">Master User</h3>
    </div><!--./ box header-->
    <div class="box-body">
      <button type="submit" class="btn btn-primary " id="btnadd" name="btnadd"><i class="fa fa-plus"></i> Add User</button>
      <br>
      <div class="box-body table-responsive no-padding">
        <table id="table_user" class="table  table-bordered table-hover ">
          <thead>
            <tr class="tableheader">
              <th style="width:30px">#</th>
              <th style="width:100px">Username</th>
              <th style="width:200px">Level</th>
              <th style="width:150px"></th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div><!-- /.box -->
</section><!-- /.content -->
<div id="modalmasteruser" class="modal fade ">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Master user Form</h4>
      </div>
      <!--modal header-->
      <div class="modal-body">
        <div class="form-horizontal">
          <div class="box-body">
            <div class="form-group">
              <label class="col-sm-2  control-label">Username</label>
              <div class="col-sm-6">
                <input type="text" class="form-control text-uppercase" id="txtusername" name="" value="" placeholder="">
                <input type="hidden" id="txtiduser" name="inputcrud" class="" value="0">
                <input type="hidden" id="inputcrud" name="inputcrud" class="" value="N">
                <input type="hidden" id="hmenu" name="" class="" value=""> </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2  control-label">Password</label>
                <div class="col-sm-6">
                  <input type="password" class="form-control " id="txtpass" name="" value="" placeholder=""> </div>
                </div>
              </div>
            </div>
            <!--form menuk-->
            <?php
            $pos = new pos();
            $mymenu = $pos->getMenu();
            $num=1;
            $menuku='';
            foreach ($mymenu[1] as $key) {
              if($num==1)
              {
                $menuku .= '<div class="row" >';
                $menuku .= '<div class="col-xs-6" style="padding-left:0px"><h4>'.$key['name_menu'].'</h4>';
                $submenuk = $pos->getSubMenu($key['id_menu']);
                $menuku .= '<ul class="list-group">'; 
                foreach ($submenuk[1] as $keys) {
                  $menuku .= '<li class="list-group-item">
                  <input type="checkbox"  id="check-'.$keys["id_sub_menu"].'" class="chkbox" value="'.$keys['id_sub_menu'].'" > <strong>'.$keys['name_sub_menu'].'</strong>
                  </li>'; 
                }
                $menuku .= '</ul>'; 
                $menuku .= '</div>';
              }else{
                $menuku .= '<div class="col-xs-6" style="padding-left:0px"><h4>'.$key['name_menu'].'</h4>';
                $submenuk = $pos->getSubMenu($key['id_menu']);
                $menuku .= '<ul class="list-group">'; 
                foreach ($submenuk[1] as $keys) {
                  $menuku .= '<li class="list-group-item"><input type="checkbox" id="check-'.$keys["id_sub_menu"].'" class="chkbox" value="'.$keys['id_sub_menu'].'" > <strong>'.$keys['name_sub_menu'].'</strong></li>'; 
                }
                $menuku .= '</ul>';
                $menuku .= '</div>';
                $menuku .= '</div>';
                $num=0;
              }
              $num++;
            }
            ?>
            <div class="form-horizontal menuk" >
              <div class="box-body">
                <div class="form-group">  
                  <label class="col-sm-2  control-label">Menu Access</label> 
                  <div class="col-xs-10">
                    <div>
                      <input type="checkbox" id="check-all" class="txtcheckbox2"> <b>Selected All</b>
                    </div>
                    <?php echo $menuku; ?>
                  </div> 
                </div>
              </div>
            </div> 
            <div class="form-horizontal">
              <div class="box-body">
                <div class="form-group">   
                  <label class="col-sm-2  control-label"></label>
                  <div class="col-sm-6">
                    <button type="submit" class="btn btn-primary " id="btnsaveuser" name="btnsaveuser"><i class="fa fa-save"></i> Save</button>
                  </div>  
                </div>
              </div>
            </div>
            <!--end form menuk-->
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
          <!--modal footer-->
        </div>
        <!--modal-content-->
      </div>
      <!--modal-dialog modal-lg-->
    </div>
    <!--form-kantor-modal-->
  </div>

  <!-- modal dialog untuk password -->
  <div id="passwordmodal" class="modal fade ">
    <div class="modal-dialog modal-md">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Reset Password</h4>
        </div><!--modal header--> 
        <div class="modal-body"><div class="form-horizontal"><div class="box-body"><div class="form-group">   <label class="col-sm-3  control-label">Reset Password</label>   <div class="col-sm-9"><input type="password" class="form-control " id="txtresetpass" name="txtresetpass" value="" placeholder=""><input type="hidden" id="txthiduser" name="" class="" value="">    </div>  </div><div class="form-group">   <label class="col-sm-3  control-label"><button type="submit" class="btn btn-primary " id="btnresetpassword" name="btnresetpassword"><i class="fa  fa-key"></i> Reset Password</button> <span id="infopassword"></span></label>   <div class="col-sm-9">    </div>  </div></div></div></div><div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div><!--modal footer-->
    </div><!--modal-content-->
  </div><!--modal-dialog modal-lg-->
</div>
<!-- end modal -->
<?php include "../layout/footer.php"; //footer template ?> 
<?php include "../layout/bottom-footer.php"; //footer template ?> 
<script src="../../plugins/datepicker/bootstrap-datepicker.js"></script>
<script src="j_mstuser.js"></script>

</body>
</html>

j_mstuser.js

$(document).ready( function () 
{
  var value = {
    method : "getdata"
  };
  $('#table_user').DataTable({
    "paging": false,
    "lengthChange": false,
    "searching": false,
    "ordering": false,
    "info": false,
    "responsive": true,
    "autoWidth": false,
    "pageLength": 50,
    "dom": '<"top"f>rtip',
    "ajax": {
      "url": "c_mstuser.php",
      "type": "POST",
      "data":value,
    },
    "columns": [
    { "data": "id_user" },
    { "data": "username" },
    { "data": "h_menu" },
    { "data": "button" },
    ]
  });
});


$(document).on("click","#check-all",function(){
  if ($(this).is(':checked')){
    $('.chkbox:enabled').prop('checked', true);
  }else{
    $('.chkbox').prop('checked', false);
  }
  get_check_value();
});
$(document).on("click",".chkbox",function(){
  get_check_value();
});
function get_check_value(){
  var values = [];
  $('.chkbox:checked').each(function() {
    values.push($(this).val());
  });
  $('#hmenu').val(values.join(','));
}
$(document).on( "click","#btnadd", function() {
  $("#modalmasteruser").modal('show');
  $("#txtiduser").val(0);
  $("#txtusername").val("");
  $("#inputcrud").val("N");
  set_focus("#txtusername");
});

$(document).on( "click",".btnedit", function() {

  var id_user = $(this).attr("id_user");
  var username = $(this).attr("username");
  var h_menu = $(this).attr("h_menu");
  $("#inputcrud").val("E");
  $("#txtiduser").val(id_user);
  $("#txtusername").val(username);
  $("#txtpass").val("***********");
  $("#hmenu").val(h_menu);
  $('.chkbox').prop('checked', false);
  var res = h_menu.split(",");
  for (i = 0; i < res.length; i++) { 
   $("#check-"+res[i]).prop('checked', true);
 }
 $("#modalmasteruser").modal('show');
 set_focus("#txtusername");
});


$(document).on( "click","#btnsaveuser", function() {
  var id_user = $("#txtiduser").val();
  var username=$("#txtusername").val();
  var pass_user=$("#txtpass").val();
  var hmenu=$("#hmenu").val();
  var crud=$("#inputcrud").val()
  if(username == '' || username== null ){
    $.notify({
      message: "Please fill out username!"
    },{
      type: 'warning',
      delay: 10000,
    });
    $("#txtusername").focus();
    return;
  }
  if(username.toUpperCase()== 'ADMIN' ){
    $.notify({
      message: "Please Do Not use 'ADMIN' as username"
    },{
      type: 'warning',
      delay: 10000,
    });
    $("#txtusername").focus();
    return;
  }
  if(pass_user == '' || pass_user == null ){
    $.notify({
      message: "Please fill out password"
    },{
      type: 'warning',
      delay: 10000,
    });
    $("#txtpass").focus();
    return;
  }
  var value = {
    id_user: id_user,
    username: username,
    pass_user:pass_user,
    h_menu : hmenu,
    crud:crud,
    method : "save_user"
  };
  $("#btnsaveuser").prop('disabled', true);
  proccess_waiting("#infoproses");
  $.ajax(
  {
    url : "c_mstuser.php",
    type: "POST",
    data : value,
    success: function(data, textStatus, jqXHR)
    {
      $("#btnsaveuser").prop('disabled', false);
      $("#infoproses").html("");
      var data = jQuery.parseJSON(data);
      if(data.crud == 'N'){
        if(data.result == true){
          $.notify("Save new user successfully");
          var table = $('#table_user').DataTable(); 
          table.ajax.reload( null, false );
          $("#txtiduser").val("");
          $("#txtusername").val("");
          $("#pass_user").val("");
          set_focus("#txtusername");

        }else{
          $.notify({
            message: "Error save new user , Error : "+data.error 
          },{
            type: 'danger',
            delay: 10000,
          });
          set_focus("#txtusername");
        }
      }else if(data.crud == 'E'){
        if(data.result == true){
          $.notify("Update user successfully");
          var table = $('#table_user').DataTable(); 
          table.ajax.reload( null, false );
          $("#modalmasteruser").modal("hide");

        }else{
          $.notify({
            message: "Error save new user , Error : "+data.error 
          },{
            type: 'danger',
            delay: 10000,
          });
          set_focus("#txtiduser");
        }
      }else{
        $.notify({
          message: "Invalid Order!" 
        },{
          type: 'danger',
          delay: 10000,
        });
      }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
      $("#btnsaveuser").prop('disabled', false);
      
    }
  });
});


$(document).on("click",".btnpass",function(){
  var id_user = $(this).attr("id_user");
  $("#txthiduser").val(id_user);
  $("#passwordmodal").modal("show");
  set_focus("#txtresetpass");
})

$(document).on("click","#btnresetpassword",function(){
 var id_user = $("#txthiduser").val();
 var new_pass = $("#txtresetpass").val();
 swal({   
  title: "Reset Password",   
  text: "Reset Password?",   
  type: "warning",   
  showCancelButton: true,   
  confirmButtonColor: "#DD6B55",   
  confirmButtonText: "Reset",   
  closeOnConfirm: true }, 
  function(){   
    var value = {
      id_user: id_user,
      new_pass : new_pass,
      crud:'D',
      method : "reset_password"
    };
    $.ajax(
    {
      url : "c_mstuser.php",
      type: "POST",
      data : value,
      success: function(data, textStatus, jqXHR)
      {
        var data = jQuery.parseJSON(data);
        if(data.result == true){
          $.notify("Reset password successfully");
          $("#passwordmodal").modal("hide");
        }else{
          $.notify({
            message: "Error reset password , Error : "+data.error 
          },{
            type: 'danger',
            delay: 10000,
          });
        }

      },
      error: function(jqXHR, textStatus, errorThrown)
      {
        $.notify({
          message:  "Error : "+textStatus
        },{
          type: 'danger',
          delay: 10000,
        });
      }
    });
  });
})

$(document).on( "click",".btndelete", function() {
  var id_user = $(this).attr("id_user");
  swal({   
    title: "Delete ",   
    text: "Delete user with id : "+id_user+" ?",   
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",   
    confirmButtonText: "Delete",   
    closeOnConfirm: true }, 
    function(){   
      var value = {
        id_user: id_user,
        crud:'D',
        method : "delete_user"
      };
      $.ajax(
      {
        url : "c_mstuser.php",
        type: "POST",
        data : value,
        success: function(data, textStatus, jqXHR)
        {
          var data = jQuery.parseJSON(data);
          if(data.result == true){
            $.notify("Delete user successfully");
            var table = $('#table_user').DataTable(); 
            table.ajax.reload( null, false );
          }else{
            $.notify({
              message: "Error delete user , Error : "+data.error 
            },{
              type: 'danger',
              delay: 10000,
            });
          }
          
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
          $.notify({
            message:  "Error : "+textStatus
          },{
            type: 'danger',
            delay: 10000,
          });
        }
      });
    });
});

c_mstuser.js

<?php
session_start();
require_ once ("../model/dbconn.php");
require_ once ("../model/pos.php");
$method=$_POST['method'];
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
	$pos = new pos();
	if($method == 'delete_user'){
		$id_user=strtoupper($_POST['id_user']);
		$pos = new pos();
		$array = $pos->deleteUser($id_user);
		$data['result'] = $array[0];
		$data['error'] = $array[1];
		echo json_encode($data);
	}

	if($method == 'getdata'){
		$pos = new pos();
		$array = $pos->getListUser();
		$data = $array[1];
		$i=0;
		foreach ($data as $key) {

			$data[$i]['button'] = '
			<button type="submit" id_user="'.$key['id_user'].'" class="btn btn-warning btnpass  btn-sm" id="btnpass'.$key['id_user'].'"  ><i class="fa fa-key"></i>
			</button>
			<button type="submit" id_user="'.$key['id_user'].'" username="'.$key['username'].'" h_menu="'.$key['h_menu'].'" class="btn btn-primary btnedit btn-sm " id="btnedit'.$key['id_user'].'"  ><i class="fa fa-edit"></i>
			</button>
			<button type="submit" id_user="'.$key['id_user'].'" class="btn  btn-danger btndelete  btn-sm " id="btndelete'.$key['id_user'].'" ><i class="fa fa-remove"></i>
				</button';


				$i++;
			}
			$datax = array('data' => $data);
			echo json_encode($datax);
		}

		if($method == 'reset_password')
		{
			$id_user= $_POST['id_user'];
			$newpass = $_POST['new_pass'];
			$pos = new pos();
			$array = $pos->resetPass($id_user,$newpass);
			$result['result'] = $array[0];
			$result['error'] = $array[1];

			echo json_encode($result);
		}

		if($method == 'save_user'){
			$id_user=$_POST['id_user'];
			$username=strtoupper($_POST['username']);
			$pass_user=strtoupper($_POST['pass_user']);
			$h_menu=strtoupper($_POST['h_menu']);
			$pos = new pos();
			if($_POST['crud'] == 'N'){
				$array = $pos->saveUser($username,$pass_user,$h_menu);
			}else{
				$array = $pos->updateUser($id_user,$username,$h_menu);
			}
			$result['result'] = $array[0];
			$result['error'] = $array[1];
			$result['crud'] = $_POST['crud'];
			echo json_encode($result);
		}
	} else {
		exit('No direct access allowed.');
	}

Add the following MySQL query list in the pos.php file:

/*********************query for master user*********************/
  public function getListUser()
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("select * from m_user where username<>'admin' order by username desc");
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }

  public function saveUser($username,$pass_user,$h_menu)
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("insert into m_user(username,pass_user,h_menu)
        values(:name,MD5(:pass),:hmenu)");

      $stmt->bindParam("name",$username);
      $stmt->bindParam("pass",$pass_user);
      $stmt->bindParam("hmenu",$h_menu);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Sukses save!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }
  public function updateUser($id_user,$username,$h_menu)
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("update m_user set username = :name, h_menu = :hmenu  where id_user = :id");

      $stmt->bindParam("name",$username);
      $stmt->bindParam("id",$id_user);
      $stmt->bindParam("hmenu",$h_menu);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Sukses update!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }
  public function deleteUser($id_user)
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("delete from m_user  where id_user = :id");

      $stmt->bindParam("id",$id_user);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Sukses update!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }

  public function checkPassword($id,$pass)
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("select * from m_user where id_user = :id and pass_user = md5(:pass)");

      $stmt->bindParam("id",$id);
      $stmt->bindParam("pass",$pass);

      $stmt->execute();
      $stat[0] = true;
      $stat[1] = $stmt->rowCount();
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }

  public function resetPass($iduser,$pass)
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("update m_user set pass_user = md5(:pass) where id_user=:id");

      $stmt->bindParam("id",$iduser);
      $stmt->bindParam("pass",$pass);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Sukses reset pass!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }

Please save all of these files and try it on your browser.

http://localhost/pos/application/utility/v_mstuser.php ,

If successful the display will be as shown below

Master User Page Tutorial Create Pos With PHP And Adminlte

Little Explanation:

Our focus on this tutorial is how do we add user access to menu. To display a list of menus contained in the database using the following script

<?php
            $pos = new pos();
            $mymenu = $pos->getMenu();
            $num=1;
            $menuku='';
            foreach ($mymenu[1] as $key) {
              if($num==1)
              {
                $menuku .= '<div class="row" >';
                $menuku .= '<div class="col-xs-6" style="padding-left:0px"><h4>'.$key['name_menu'].'</h4>';
                $submenuk = $pos->getSubMenu($key['id_menu']);
                $menuku .= '<ul class="list-group">'; 
                foreach ($submenuk[1] as $keys) {
                  $menuku .= '<li class="list-group-item">
                  <input type="checkbox"  id="check-'.$keys["id_sub_menu"].'" class="chkbox" value="'.$keys['id_sub_menu'].'" > <strong>'.$keys['name_sub_menu'].'</strong>
                  </li>'; 
                }
                $menuku .= '</ul>'; 
                $menuku .= '</div>';
              }else{
                $menuku .= '<div class="col-xs-6" style="padding-left:0px"><h4>'.$key['name_menu'].'</h4>';
                $submenuk = $pos->getSubMenu($key['id_menu']);
                $menuku .= '<ul class="list-group">'; 
                foreach ($submenuk[1] as $keys) {
                  $menuku .= '<li class="list-group-item"><input type="checkbox" id="check-'.$keys["id_sub_menu"].'" class="chkbox" value="'.$keys['id_sub_menu'].'" > <strong>'.$keys['name_sub_menu'].'</strong></li>'; 
                }
                $menuku .= '</ul>';
                $menuku .= '</div>';
                $menuku .= '</div>';
                $num=0;
              }
              $num++;
            }
            ?>

From the code above we can show the layout like image below:

Create Access Menu Module In Master User Page

You can add some parameters you need to the user module. Up here how to create the master user page module on point of sale PHP has been completed, my next article will discuss how to create a page to add new items/product.

Once again this is a tutorial for beginners, if you are already expert please provide feedback for this article, for those who still do not understand please ask through the comment form below

So my article about Create Form User – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 3. Hopefully, useful

Create Master Item / Product Form – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 4.

$
0
0

How to create master item form at the point of sale PHP. Finally, we have come to part 4, This article will discuss how to create a master item page where the system can add, edit and delete items from the database. Let’s start the following tutorial.

To start this section, you should read the 3 previous articles in order to understand it. In Part 1 I discuss how to create a login form. Then in part 2, I discuss how to create a dynamic menu on adminLTE. In part 3, I created a master user form to give users access to each menu. Here’s the previous part URL address

Let’s begin the tutorial.

How To Create Master Item Page in Point Of Sale PHP

Tutorial How To Create Master Item Page

In this part 4 we will create four new files in the “sales” folder (pos/application/sales/): c_search_item.php, v_item.php, c_item.php and. j_item.js. Additionally, we will add a list of MYSQL queries to the master items (m_item table) in the pos.php file (pos/application/model/pos.php). Copy the following code in each PHP and javascript file.

c_search_item.php

<?php
session_start();
require_ once ("../model/dbconn.php");
require_ once ("../model/pos.php");
function cmp($a, $b) {
	return strcmp($a["id_item"], $b["id_item"]);
}
$term = $_POST['term'];
$pos = new pos();
$html ='';

$data = $pos->autoCompleteItem($term);
$hasil = array();
$i=1;
foreach ($data[1] as $row) 
{
	$hasil[$i]['item_name'] = $row['item_name'];
	$hasil[$i]['id_item'] = $row['id_item'];
	$hasil[$i]['unit'] = $row['unit'];
	$hasil[$i]['price'] = $row['price'];
	$hasil[$i]['stock'] = $row['stock'];
	$i++;
}
usort($hasil, "cmp");
$no = 1;
foreach($hasil as $key)
{
	$html .= '<tr>';
	$html .= '<td>'.$no.'</td>';
	$html .= '<td>'.$key['id_item'].'</td>';
	$html .= '<td>'.$key['item_name'].'</td>';
	$html .= '<td style="text-align:right">'.number_format($key['price']).'</td>';
	$html .= '<td style="text-align:right">'.$key['stock'].$key['unit'].'</td>';	

	$html .= '</tr>';
	$no++;
}

$array = array();
$array['data'] = $html;
echo json_encode($array);

c_search_item.php used to show item list in the index page dashboard. After create this module, check your dashboard or index page and then try search the item in the text box. If successful the result like the following image:

Dashboard Page Search Item

v_item.php

<?php 
$titlepage="Master Item";
$idsmenu=1; 
include "../../library/config.php";
require_ once("../model/dbconn.php");
require_ once("../model/pos.php");
include "../layout/top-header.php";
include "../../library /check_login.php";
include "../../library /check_access.php";
include "../layout/header.php"; ?>

<section class="content">
	<div class="box box-success">
		<div class="box-header with-border">
			<h3 class="box-title">Master Item</h3>
		</div>
		<!--./ box header-->
		<div class="box-body">
			<div class="row">
				<div class="col-md-6">
					<button type="submit" class="btn btn-primary " id="btnadd" name=""><i class="fa fa-plus"></i> Add Item</button>
					<br>
				</div>
			</div>
			<div class="box-body table-responsive no-padding" style="max-width:1124px;">
				<table id="table_item" class="table  table-bordered table-hover ">
					<thead>
						<tr class="tableheader">
							<th style="width:40px">#</th>
							<th style="width:60px">Id</th>
							<th style="width:300px">Item</th>
							<th style="width:120px">Price</th>
							<th style="width:60px">Stok</th>
							<th style="width:250px">Note</th>
							<th></th>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>		
		</div>
	</div><!-- /.box -->

</section><!-- /.content -->

<div id="modalmasteritem" class="modal fade ">
	<div class="modal-dialog modal-md">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">×</button>
				<h4 class="modal-title">Master Item Form</h4>
			</div>
			<!--modal header-->
			<div class="modal-body">
				<div class="form-horizontal">
					<div class="box-body">
						<div class="form-group"> <label class="col-sm-1  control-label">Id</label>
							<div class="col-sm-11"><input type="text" class="form-control " id="txtiditem" name="txtiditem" value="*New" placeholder="" disabled=""><input type="hidden" id="inputcrud" name="inputcrud" class="" value="N"> </div>
						</div>
						<div class="form-group"> <label class="col-sm-1  control-label">Item</label>
							<div class="col-sm-11"><input type="text" class="form-control " id="txtname" name="txtname" value="" placeholder="Please fill out item name"> </div>
						</div>
						<div class="form-group"> <label class="col-sm-1  control-label">Stok</label>
							<div class="col-sm-11"><input type="text" class="form-control decimal" id="txtstock" name="" value="0" placeholder=""> </div>
						</div>
						<div class="form-group"> <label class="col-sm-1  control-label">Unit</label>
							<div class="col-sm-11"><input type="text" class="form-control " id="txtunit" name="" value="" placeholder="Please fill out unit name"> </div>
						</div>
						<div class="form-group"> <label class="col-sm-1  control-label">Price</label>
							<div class="col-sm-11">
								<div class="input-group">
									<span class="input-group-addon">Rp.</span>
									<input type="text" class="form-control money" id="txtprice" name="" value="" placeholder=""></div>
								</div>
							</div>
							<div class="form-group"> <label class="col-sm-1  control-label">Note</label>
								<div class="col-sm-11"><textarea class="form-control " rows="3" id="txtnote" name="" placeholder="Note"></textarea> </div>
							</div>
							<div class="form-group"> <label class="col-sm-1  control-label"></label>
								<div class="col-sm-11"><button type="submit" title="Save Button" class="btn btn-primary " id="btnsaveitem" name=""><i class="fa fa-save"></i> Save</button> <span id="infoproses"></span> </div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				</div>
				<!--modal footer-->
			</div>
			<!--modal-content-->
		</div>
		<!--modal-dialog modal-lg-->
	</div>


	<?php include "../layout/footer.php"; //footer template ?> 
	<?php include "../layout/bottom-footer.php"; //footer template ?> 
	<script src="j_item.js"></script>
</body>
</html>

v_item.php used to create the master item page.

c_item.php

<?php
session_start();
require_ once ("../model/dbconn.php");
require_ once ("../model/pos.php");
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
	$pos = new pos();
	$method=$_POST['method'];
	if($method == 'get_detail_item')
	{
		$id_item=$_POST['id_item'];
		$pos = new pos();
		$data = $pos->getItem($id_item);
		$array['data'] = $data[1];
		$array['result'] = $data[0];
		echo json_encode($array);
	}
	if($method == 'save_item')
	{
		$iditem = $_POST['id_item'];
		$nameitem = $_POST['item_name'];
		$unit= $_POST['unit'];
		$stock = $_POST['stock'];
		$price = $_POST['price'];
		$note = $_POST['note'];
		$crud=$_POST['crud'];
		$pos = new pos();
		if($_POST['crud'] == 'N')
		{
			$array = $pos->saveItem($nameitem,$price,$unit,$stock,$note);
			if($array[0] == true)
			{
				$result['id_item'] = $array[2];
			}
			
		}
		else
		{
			$array = $pos->updateItem($iditem,$nameitem,$price,$unit,$stock,$note);
		}
		$result['result'] = $array[0];
		$result['error'] = $array[1];
		$result['crud'] = $_POST['crud'];
		echo json_encode($result);
	}
	
	if($method == 'getdata'){
		$pos = new pos();
		$array = $pos->getListItem();
		$data = $array[1];
		$i=0;
		foreach ($data as $key) {
			$button = '<button  type="submit" id_item="'.$key['id_item'].'"  title="Tombol edit barang" class="btn btn-sm btn-primary btnedit "  id="btnedit'.$key['id_item'].'"  ><i class="fa fa-edit"></i></button> <button  type="submit" id_item="'.$key['id_item'].'"  title="Tombol hapus barang" class="btn btn-danger btn-sm btndelete "  id="btndelete'.$key['id_item'].'"  ><i class="fa fa-trash"></i></button>';

			$data[$i]['price'] =  number_format($data[$i]['price']);
			$data[$i]['DT_RowId']= $data[$i]['id_item'];
			$data[$i]['stock']= number_format($data[$i]['stock']);
			$data[$i]['button'] = $button;
			$i++;
		}
		$datax = array('data' => $data);
		echo json_encode($datax);
	}
	if($method == 'delete_item'){
		$id_item=$_POST['id_item'];
		$pos = new pos();
		$array = $pos->deleteItem($id_item);
		$data['result'] = $array[0];
		$data['error'] = $array[1];
		echo json_encode($data);
	}
	
} else {
	exit('No direct access allowed.');
}

c_item is a master item backend. All of PHP function to manipulate data in master item placed in this file.

j_item.js

$(document).ready( function () 
{
	money();
	decimal();
	var value = {
		method : "getdata"
	};
	$('#table_item').DataTable({
		"paging": true,
		"lengthChange": false,
		"searching": true,
		"ordering": true,
		"info": false,
		"responsive": true,
		"autoWidth": false,
		"pageLength": 50,
		"dom": '<"top"f>rtip',
		"ajax": {
			"url": "c_item.php",
			"type": "POST",
			"data":value,
		},
		"columns": [
		{ "data": "urutan" },
		{ "data": "id_item" },
		{ "data": "item_name" },
		{ "data": "price" },
		{ "data": "stock" },
		{ "data": "note" },
		{ "data": "button" },
		]
	});
	$("#table_item_filter").addClass("pull-right");
});

$(document).on( "click","#btnadd", function() {
	$(".contentharga").remove();
	$("#modalmasteritem").modal('show');
	newitem();
});
function newitem()
{
	$("#txtiditem").val("*New");
	$("#txtname").val("");
	$("#txtstock").val(0);
	$("#txtprice").val(0);
	$("#txtnote").val("");
	$("#inputcrud").val("N");
	$("#txtunit").change();
	set_focus("#txtname");
}
$(document).on( "click",".btnedit", function() {
	var id_item = $(this).attr("id_item");
	var value = {
		id_item: id_item,
		method : "get_detail_item"
	};
	$.ajax(
	{
		url : "c_item.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var hasil = jQuery.parseJSON(data);
			data = hasil.data;
			$("#inputcrud").val("E");
			$("#txtiditem").val(data.id_item);
			$("#txtname").val($.trim(data.item_name));
			$("#txtunit").val($.trim(data.unit));
			$("#txtstock").val(data.stock);
			$("#txtprice").val(addCommas(data.price));
			$("#txtnote").val($.trim(data.note));
			$("#modalmasteritem").modal('show');
			set_focus("#txtname");
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
		}
	});
});
$(document).on( "click","#btnsaveitem", function() {
	var id_item = $("#txtiditem").val();
	var item_name = $("#txtname").val();
	var unit = $("#txtunit").val();
	var stock = cleanString($("#txtstock").val());
	var price = cleanString($("#txtprice").val());
	var note = $("#txtnote").val();
	var crud=$("#inputcrud").val();
	if(crud == 'E'){
		if(id_item == '' || id_item== null ){
			$.notify({
				message: "Item Id invalid"
			},{
				type: 'warning',
				delay: 8000,
			});		
			$("#txtiditem").focus();
			return;
		}	
	}
	if(item_name == '' || item_name== null ){
		$.notify({
			message: "Please fill out item name"
		},{
			type: 'warning',
			delay: 8000,
		});		
		$("#txtname").focus();
		return;
	}

	var value = {
		id_item: id_item,
		item_name: item_name,
		unit:unit,
		stock:stock,
		price:price,
		note:note,
		crud:crud,
		method : "save_item"
	};
	$(this).prop('disabled', true);
	proccess_waiting("#infoproses");
	$.ajax(
	{
		url : "c_item.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			$("#btnsaveitem").prop('disabled', false);
			$("#infoproses").html("");
			var data = jQuery.parseJSON(data);
			if(data.ceksat == 0){
				$.notify(data.error);
			}else{
				if(data.crud == 'N'){
					if(data.result == 1){
						$.notify('Save item successfuly');
						var table = $('#table_item').DataTable(); 
						table.ajax.reload( null, false );
						newitem();				
					}else{
						$.notify({
							message: "Error save item, error :"+data.error
						},{
							type: 'danger',
							delay: 8000,
						});
						set_focus("#txtiditem");
					}
				}else if(data.crud == 'E'){
					if(data.result == 1){
						$.notify('Update item successfuly');
						var table = $('#table_item').DataTable(); 
						table.ajax.reload( null, false );
						$("#modalmasteritem").modal("hide");
					}else{
						$.notify({
							message: "Error update item, error :"+data.error
						},{
							type: 'danger',
							delay: 8000,
						});					
						set_focus("#txtiditem");
					}
				}else{
					$.notify({
						message: "Invalid request"
					},{
						type: 'danger',
						delay: 8000,
					});	
				}
			}
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			$("#btnsaveitem").prop('disabled', false);
		}
	});
});
$(document).on( "click",".btndelete", function() {
	var id_item = $(this).attr("id_item");
	swal({   
		title: "Delete",   
		text: "Delete master item with id : "+id_item+" ?",   
		type: "warning",   
		showCancelButton: true,   
		confirmButtonColor: "#DD6B55",   
		confirmButtonText: "Delete",   
		closeOnConfirm: true }, 
		function(){   
			var value = {
				id_item: id_item,
				method : "delete_item"
			};
			$.ajax(
			{
				url : "c_item.php",
				type: "POST",
				data : value,
				success: function(data, textStatus, jqXHR)
				{
					var data = jQuery.parseJSON(data);
					if(data.result ==1){
						$.notify('Delete item successfuly');
						var table = $('#table_item').DataTable(); 
						table.ajax.reload( null, false );
					}else{
						$.notify({
							message: "Error delete item, error :"+data.error
						},{
							type: 'eror',
							delay: 8000,
						});	
					}
				},
				error: function(jqXHR, textStatus, errorThrown)
				{
				}
			});
		});
});

Add the following code to pos.php

/******************************************************************************
    START TABEL m_item
    *******************************************************************************/
    public function getListItem()
    {
      $db = $this->dblocal;
      try
      {
       $stmt = $db->prepare("SELECT @rownum := @rownum + 1 AS urutan,t.* FROM m_item t, 
        (SELECT @rownum := 0) r ORDER BY id_item ASC");
       $stmt->execute();
       $stat[0] = true;
       $stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
       return $stat;
     }
     catch(PDOException $ex)
     {
       $stat[0] = false;
       $stat[1] = $ex->getMessage();
       return $stat;
     }
   }

   public function getItem($id_item){
    $db = $this->dblocal;
    try
    {
     $stmt = $db->prepare("select a.* from m_item a where a.id_item = :id ");
     $stmt->bindParam("id",$id_item);
     $stmt->execute();
     $stat[0] = true;
     $stat[1] = $stmt->fetch(PDO::FETCH_ASSOC);
     return $stat;
   }
   catch(PDOException $ex)
   {
     $stat[0] = false;
     $stat[1] = $ex->getMessage();
     return $stat;
   }
 }


 public function updateItem($iditem,$item_name,$price,$unit,$stock,$note)
 {
  $db = $this->dblocal;
  try
  {
   $stmt = $db->prepare("UPDATE m_item 
    SET  item_name = UPPER(:item_name),
    unit= :unit,
    stock= :stock, 
    price= :price,
    note= :note 
    WHERE id_item= :iditem;");

   $stmt->bindParam("iditem",$iditem);
   $stmt->bindParam("item_name",$item_name);
   $stmt->bindParam("price",$price);
   $stmt->bindParam("note",$note);
   $stmt->bindParam("unit",$unit);
   $stmt->bindParam("stock",$stock);

   $stmt->execute();
   $stat[0] = true;
   $stat[1] = "Success Edit!";
   return $stat;
 }
 catch(PDOException $ex)
 {
   $stat[0] = false;
   $stat[1] = $ex->getMessage();
   return $stat;
 }
}

public function saveItem($item_name,$price,$unit,$stock,$note){
  $db = $this->dblocal;
  try
  {
   $stmt = $db->prepare("call saveItem(:item_name,:unit,:stock,:price,:note)");
   $stmt->bindParam("item_name",$item_name);
   $stmt->bindParam("price",$price);
   $stmt->bindParam("note",$note);
   $stmt->bindParam("unit",$unit);
   $stmt->bindParam("stock",$stock);
   $stmt->execute();
   $stat[0] = true;
   $stat[1] = "Success save!";
   $stat[2] =  $stmt->fetchColumn(0);
   return $stat;
 }
 catch(PDOException $ex)
 {
   $stat[0] = false;
   $stat[1] = $ex->getMessage();
   return $stat;
 }
}

public function deleteItem($iditem)
{
  $db = $this->dblocal;
  try
  {
   $stmt = $db->prepare("delete from m_item where id_item = :id");
   $stmt->bindParam("id",$iditem);
   $stmt->execute();
   $stat[0] = true;
   $stat[1] = "Success Delete!";
   return $stat;
 }
 catch(PDOException $ex)
 {
   $stat[0] = false;
   $stat[1] = $ex->getMessage();
   return $stat;
 }
}

public function autoCompleteItem($term)
{
  $trm = "%".$term."%";
  $db = $this->dblocal;
  try
  {
   $stmt = $db->prepare("SELECT a.* FROM m_item a WHERE  item_name like :term or id_item  like :term order by item_name asc");
   $stmt->bindParam("term",$trm);
   $stmt->execute();
   $stat[0] = true;
   $stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
   return $stat;
 }
 catch(PDOException $ex)
 {
   $stat[0] = false;
   $stat[1] = $ex->getMessage();
   return $stat;
 }
}
 /*******************************************************************************
 END OF TABEL M_Item
 *******************************************************************************/

Don’t forget to add new table m_item with table structure like the following image:

M Item Table

Add new store procedures in the database. Execute the script below to create saveItem store procedures

DELIMITER $$

USE 'pos'$$

DROP PROCEDURE IF EXISTS 'saveItem'$$

CREATE  PROCEDURE 'saveItem'(var_item_name VARCHAR(100),var_unit VARCHAR(4),var_stock INT,var_price INT,var_note TEXT)
BEGIN
	DECLARE newnumber,newiditem VARCHAR(6);
	DECLARE countitem INT;
		SELECT COUNT(id_item) FROM m_item INTO countitem;
		IF(countitem = 0 ) THEN
			SET newnumber = '1';
		ELSE
			SELECT TRIM(CAST((CAST(SUBSTR(id_item,3,6) AS UNSIGNED)+1) AS CHAR(4)))    
			FROM m_item 
			ORDER BY id_item DESC LIMIT 1 INTO newnumber;
		END IF; 
		IF (LENGTH(newnumber) = 1) THEN
			SET newiditem=CONCAT('PB000',newnumber);
		ELSE
			IF (LENGTH(newnumber) = 2) THEN
				SET newiditem=CONCAT('PB00',newnumber);
			ELSE
				IF (LENGTH(newnumber) = 3) THEN
					SET newiditem=CONCAT('PB0',newnumber);
				ELSE
					SET newiditem=CONCAT('PB',newnumber);
				END IF ;
			END IF ;
		END IF ;
		 INSERT INTO m_item(id_item,item_name,unit,stock,price,note)
		 	VALUES(newiditem,var_item_name,var_unit,var_stock,var_price,var_note);
		 SELECT newiditem AS id_item;
    END$$

DELIMITER ;

Until this part, We have created 5 tables and a MySQL store procedure.

Pos Database Structure Mysql

Please test in your browser and make sure the system works as shown below:

Master Item Page Tutorial Point Of Sale Php

Up to this point, the tutorial how to create master item page in point of sale php has been completed. The last step we will make the core of this application: making a sales system/simple point of sale in php and adminLTE. If there is any question please fill in the comment field at the end of the paragraph.

This complete point of sale project can be downloaded in part 5 of the article.

So my article about the Create Master Items/Product Page in point of sale with PHP and jquery.


Create a Sales Form / POS – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 5

$
0
0

How to create a sales transactions page with PHP, jquery, and adminLTE. We have been at the end of the tutorial create a point of sale system with PHP. This article was the initial goal of the tutorial create a point of sale with PHP and AdminLTE. In this article, I will discuss how to create a simple sales page. In addition, the complete source of this project will share on this part. Let’s follow the tutorial

For those of you who don’t follow the tutorial from the first, please read them in advance every part via the following URL links.

Sales form is used to manage sales transactions. Every sale transaction done will reduce stock items and print struck sales. This module is still very simple because it is only used as a learning process.

Tutorial Create a sales page with PHP, PDO, jquery and adminLTE

Database Preparation

Add 3 new tables in “pos” database: t_sale, t_sale_detail, temp_sale. To create 3 tables above please see the structure of the table in the following image:

Pos Structure Table

A little explanation of the table:

t_sale is used to store primary data on sales transactions. Table t_sale_detail to store details of items that are on sale transaction with the certain transaction code. And the temp_sale table is used to store temporary of detail items, and the data in the temp_sale will be deleted when the transaction is successfully saved and or at the beginning of login, all of the temp_sale data on the user will be emptied.

Please create 3 new store procedure: saveSale, deleteSale, restore_stock_sale

saveSale

DELIMITER $$

USE 'pos'$$

DROP PROCEDURE IF EXISTS 'saveSale'$$

CREATE PROCEDURE 'saveSale'(pre_sale_id VARCHAR(7), var_sale_date DATE
    , var_paid INT,discprcn DECIMAL(5,2),discrp INT,var_unique VARCHAR(13)
    ,iduser INT,var_note TEXT)
BEGIN
    DECLARE v_finished INTEGER DEFAULT 0;
    DECLARE next_sale_id,next_value VARCHAR(10);
    DECLARE count_of_sale INT;
    DECLARE cid_item VARCHAR(6);
    DECLARE cname VARCHAR(100);
    DECLARE cqty,cdiscrp,cprice  INT;
    DECLARE cunit VARCHAR(4);
    DECLARE cdiscprc DECIMAL(5,2);
    DECLARE tempsale CURSOR FOR SELECT id_item,item_name,qty,unit,price,discprc,discrp  FROM temp_sale WHERE uniqid = var_unique AND id_user = iduser ;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
	
	SELECT COUNT(sale_id) FROM t_sale WHERE SUBSTR(sale_id,1,7) = pre_sale_id  INTO count_of_sale;
	IF count_of_sale = 0 THEN
		SET next_value = '1';
	ELSE
		SELECT TRIM(CAST((CAST(SUBSTR(sale_id,8,3) AS UNSIGNED)+1) AS CHAR(3)))
		FROM t_sale 
		WHERE SUBSTR(sale_id,1,7) = pre_sale_id 
		ORDER BY sale_id DESC LIMIT 1 INTO next_value;
	END IF;
	IF (LENGTH(next_value) = 1) THEN
			SET next_sale_id=CONCAT(pre_sale_id,'00',next_value);
	ELSE
			IF (LENGTH(next_value) = 2) THEN
				SET next_sale_id=CONCAT(pre_sale_id,'0',next_value);
			ELSE
				SET next_sale_id=CONCAT(pre_sale_id,next_value);
			END IF ;
	END IF ;
	INSERT INTO t_sale(sale_id,id_user,sale_date, paid,disc_prcn,disc_rp,sts,note) VALUES
	(next_sale_id,iduser,var_sale_date,var_paid,discprcn,discrp,1,var_note);
	
	OPEN tempsale;
	get_tempsale: LOOP
	FETCH tempsale INTO cid_item,cname,cqty,cunit,cprice,cdiscprc,cdiscrp;
	IF v_finished = 1 THEN 
		LEAVE get_tempsale;
	END IF;
	 
		INSERT INTO t_sale_detail(sale_id,id_item,item_name,qty,unit,price,disc_prc,disc_rp) VALUES
		(next_sale_id,cid_item,cname,cqty,cunit,cprice,cdiscprc,cdiscrp);
			UPDATE m_item SET stock = stock - cqty WHERE id_item = cid_item;
		
	END LOOP get_tempsale;
        CLOSE tempsale;
        SELECT next_sale_id;
    END$$

DELIMITER ;

saveSale store procedure is used to store transactions into the database.

deleteSale

DELIMITER $$

USE 'pos'$$

DROP PROCEDURE IF EXISTS 'deleteSale'$$

CREATE DEFINER='root'@'localhost' PROCEDURE 'deleteSale'(x_sale_id VARCHAR(10),cnote TEXT)
BEGIN
	CALL restore_stock_sale(x_sale_id);
	UPDATE t_sale SET sts = 0,note = cnote WHERE sale_id= x_sale_id;
    END$$

DELIMITER ;

deleteSale store procedure is used to remove sales transactions from the database. The sales transaction is not deleted with DELETE MySQL function but only UPDATE MySQL by changing the sts field to 0. Because in Information system security, a transaction history is very important.

restore_stock_sale

DELIMITER $$

USE 'pos'$$

DROP PROCEDURE IF EXISTS 'restore_stock_sale'$$

CREATE DEFINER='root'@'localhost' PROCEDURE 'restore_stock_sale'(var_sale_id VARCHAR(10))
BEGIN
	DECLARE v_finished INTEGER DEFAULT 0;
    DECLARE cid_item VARCHAR(6);
    DECLARE cqty INT;
    DECLARE deletesale CURSOR FOR SELECT id_item,qty FROM t_sale_detail WHERE sale_id = var_sale_id ;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
	
	OPEN deletesale;
	get_deletesale: LOOP
	FETCH deletesale INTO cid_item,cqty;
	IF v_finished = 1 THEN 
		LEAVE get_deletesale;
	END IF;
	 	UPDATE m_item SET stock = stock + cqty WHERE id_item = cid_item;	
	END LOOP get_deletesale;
        CLOSE deletesale;
        
    END$$

DELIMITER ;

restore_stock_sale store procedure is used to restore stock items as they were when sales transactions were removed.

In this section, we will add 4 new files in the sales folder (pos/application/sales/) and edit the pos.php file to add a list of MySQL queries in the sales table. Copy the following code on each file

autocomplete_item.php

<?php
session_start();
require _once ("../model/dbconn.php");
require _once ("../model/pos.php");

$term = trim(strip_tags($_GET['term']));
$row_set = array();
$pos = new pos();

$data = $pos->autoCompleteItem($term);
foreach ($data[1] as $row) {
	$row['label']=htmlentities(stripslashes($row['item_name']));
	$row['value']=htmlentities(stripslashes($row['item_name']));
	if($row['note'] == '' or $row['note'] == null){
		$row['note']='';
	}else{
		$row['note']='<dd><small> Note : '.$row['note'].'</small></dd>';
	}
	$row['price']='<dd><small> Rp.'.number_format($row['price']).' /'.$row['unit'].'</small></dd>';

	$row['id_item']=$row['id_item'];
	$row['unit']=$row['unit'];
	$row_set[] = $row;
}

echo json_encode($row_set);
?>

v_pos.php

<?php 
$titlepage="POINT OF SALE";
$idsmenu=2;
include "../../library/config.php";
require _once("../model/dbconn.php");
require _once("../model/pos.php");
include "../layout/top-header.php"; 
include "../../library/check_login.php";
include "../../library/check_access.php";
?> 
<link rel="stylesheet" href="../../dist/css/bootstrap-switch.min.css">
<link rel="stylesheet" href="../../plugins/datepicker/datepicker3.css">
<?php include "../layout/header.php"; ?>
<section class="content">
	<div class="row">
		<div class="col-md-8">
			<div class="box box-success">
				<div class="box-header with-border">
					<h3 class="bordercool">Point Of Sale</h3>
					<input type="text" class="form-control text-uppercase" id="txtsearchitem"  placeholder="Search item name or item id here...">				
				</div><!--./ box header-->
				<div class="box-body">
					<div class="box-body table-responsive no-padding">
						<table id="table_transaction" class="table  table-bordered table-hover ">
							<thead>
								<tr class="tableheader">
									<th style="width:40px">#</th>
									<th style="width:60px">Id</th>
									<th style="width:250px">Item</th>
									<th style="width:120px">Price</th>
									<th style="width:60px">Qty</th>
									<th style="width:60px">Disc %</th>
									<th style="width:120px">Total</th>
									<th style="width:px"></th>
								</tr>
							</thead>
							<tbody></tbody>
						</table>

					</div>				
				</div><!-- /.box-body -->
			</div><!-- /.box -->
		</div><!-- /.col-md-8 -->
		<div class="col-md-4">
			<div class="box box-danger">
				<div class="box-header with-border">
					<button type="submit" title="Reset / cancel transaction" class="btn btn-primary bg-navy" id="btncancel" ><i class="fa fa-remove"></i> Reset</button> 				
				</div><!--./ box header-->
				<div class="box-body">
					<div class="form-horizontal">
						<div class="box-body">
							<div class="form-group">   
								<label class="col-sm-3  control-label">Id Trans.</label>
								<div class="col-sm-9">
									<div class="input-group ">
										<input type="text" class="form-control " id="txtidsales"  value="J160412###"  disabled>
										<span class="input-group-btn ">
											<button type="submit" title="Get last transaction" class="btn btn-primary " id="btnopentransaction" name="btnopentransaction">
												<i class="fa  fa-search"></i>
											</button>
										</span>
									</div>    
								</div>  
							</div>
							<div class="form-group">   
								<label class="col-sm-3  control-label">Date Trans.</label>   
								<div class="col-sm-9">
									<input readonly="" type="text" class="form-control txtsalesdate" id="txtsalesdate"  value="20-04-2017" >
								</div>
							</div>
							<div class="form-group">
								<label class="col-sm-3  control-label">Cashier</label>
								<div class="col-sm-9">
									<input type="text" class="form-control " id="txtchasiername"  value="admin"  disabled>
								</div>
							</div>
							<div class="form-group">
								<label class="col-sm-3  control-label"><a href="#" class="btndisc btndiscprc">Dsc %</a></label>   <div class="col-sm-9">
								<div class="input-group ">
									<input type="text" class="form-control decimal" id="txttotaldiscprc"  value="0" >
									<span class="input-group-addon ">%</span>
								</div>    
							</div>  
						</div>
						<div class="form-group">  
							<label class="col-sm-3  control-label"><a href="#" class="btndisc btndiscrp">Dsc Rp</a></label>  
							<div class="col-sm-9">
								<div class="input-group">
									<span class="input-group-addon">Rp.</span>
									<input type="text" class="form-control money textright" id="txttotaldiscrp" name="txttotaldiscrp" value="0"  disabled>
								</div>  
							</div> 
						</div>
						<div class="form-group">  
							<label class="col-sm-3  control-label">Sub Total</label> 
							<div class="col-sm-9">
								<div class="input-group">
									<span class="input-group-addon">Rp.</span>
									<input type="text" class="form-control " id="txtsubtotal"  value="0"  disabled>
								</div>   
							</div>  
						</div>
					</div>
				</div>
				<div class="info-box" style="margin-top:15px;">
					<span class="info-box-icon bg-yellow">Rp.</span>
					<div class="info-box-content">
						<span class="info-box-number newbox" id="txttotal">0</span>
					</div><!-- /.info-box-content -->
				</div>
				<div class="form-horizontal">
					<div class="box-body">
						<div class="form-group">
							<label class="col-sm-12" control-label="">
								<button type="submit" title="Payment (F9)" class="btn btn-primary btn-success btn-block btnpayment" id="btnpayment" >
									<i class="fa fa-shopping-cart"></i>[F9] Proccess Payment
								</button>
							</label>  
						</div>
					</div>
				</div>		
			</div>
			<!-- /.box-body -->
		</div><!-- /.box -->
	</div><!-- /.col-md-4 -->
</div><!-- /.row -->
</section><!-- /.content -->


<div id="modaleditparam" class="modal fade ">
	<div class="modal-dialog modal-sm">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">×</button>
				<h4 class="modal-title">Edit</h4>
			</div><!--modal header--> 
			<div class="modal-body">
				<div class="form-horizontal">
					<div class="box-body">
						<div class="form-group">  
							<label class="col-sm-12" control-label="">
								<input type="text" class="form-control money textright" id="txtvalue" name="txtvalue"  >
								<input type="hidden" id="txtdataparam" >
								<input type="hidden" id="txtkey">
							</label>  
						</div>
						<div class="form-group">  
							<label class="col-sm-2  control-label">
								<button type="submit" class="btn btn-primary " id="btnubahedit" >
									<i class="fa fa-edit"></i> Edit
								</button> 
								<span id="infoproses"></span>
							</label> 
							<div class="col-sm-10"> 
							</div> 
						</div>
					</div>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
			</div><!--modal footer-->
		</div><!--modal-content-->
	</div><!--modal-dialog modal-lg-->
</div><!--modaleditparam-->

<div id="modalpayment" class="modal fade ">
	<div class="modal-dialog modal-md">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">×</button>
				<h4 class="modal-title"></h4>
				<h3><i class="fa fa-shopping-cart"></i> Payment</h3>
			</div><!--modal header-->
			<div class="modal-body">
				<div class="form-horizontal">
					<div class="box-body">
						<div class="form-group">
							<label class="col-sm-4  control-label">Transaction Id</label>
							<div class="col-sm-8">
								<input type="text" class="form-control " id="txtinfoidtrans"    disabled=""> </div>
							</div>
							<div class="form-group">
								<label class="col-sm-4  control-label">Transaction Date</label>
								<div class="col-sm-8">
									<input type="text" class="form-control " id="txtinfodatetrans"    disabled=""> </div>
								</div>
								<div class="form-group">
									<label class="col-sm-4  control-label">Total Payable Amount</label>
									<div class="col-sm-8">
										<div class="input-group">
											<span class="input-group-addon">Rp.</span>
											<input type="text" class="form-control money textright" id="txtgrandtotal"  value="0"  disabled="">
										</div>
									</div>
								</div>
								<div class="form-group">
									<label class="col-sm-4  control-label">Paid</label>
									<div class="col-sm-8">
										<div class="input-group">
											<span class="input-group-addon">Rp.</span>
											<input type="text" class="form-control money textright" id="txtmoneypay"  value="0" >
										</div>
									</div>
								</div>
								<div class="form-group">
									<label class="col-sm-4  control-label">Return Change</label>
									<div class="col-sm-8">
										<div class="input-group">
											<span class="input-group-addon">Rp.</span>
											<input type="text" class="form-control money textright" id="txtoddmoney"  value="0"  disabled="">
										</div>
									</div>
								</div>
								<div class="form-group">
									<label class="col-sm-4  control-label">Note</label>
									<div class="col-sm-8">
										<textarea class="form-control " maxlength="100" rows="3" id="txtnote"  placeholder="Max 100 words"></textarea>
									</div>
								</div>
								<div class="form-group">
									<label class="col-sm-12" control-label "=" "><hr></label>  </div><div class="form-group ">   <label class="col-sm-12 " control-label"=""><span style="color:white;background-color:red;padding:5px;">* Please double check the transaction before making the payment process </span>
								</label>
							</div>
							<div class="form-group">
								<label class="col-sm-4  control-label"></label>
								<div class="col-sm-8">
									<button type="submit" title="Save Transaction ?" class="btn btn-primary pull-right" id="btnsavetrans" ><i class="fa fa-save"></i> Proccess</button>
								</div>
							</div>
							<div class="form-group">
								<label class="col-sm-4  control-label"><span id="infoproccesspayment"></span>
								</label>
								<div class="col-sm-8"> </div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				</div>
				<!--modal footer-->
			</div>
			<!--modal-content-->
		</div>
		<!--modal-dialog modal-lg-->
	</div>

	<div id="modallasttrans" class="modal fade ">
		<div class="modal-dialog modal-md">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">×</button>
					<h4 class="modal-title">Lists of transaction</h4>
				</div>
				<!--modal header-->
				<div class="modal-body">
					<div class="form-group">
						<label for="Periode">Period : </label>
						<input readonly="" type="text" class="form-control txtperiode tgl" id="txtfirstperiod"  value="20-04-2017"  style="width:100px "> -
						<input readonly="" type="text" class="form-control txtperiode tgl" id="txtlastperiod"  value="20-04-2017"  style="width:100px ">
						<button type="submit" title="Search transaction" class="btn btn-primary " id="btnfiltersale" ><i class="fa fa-refresh"></i> Search</button>
					</div>
					<hr>
					<div class="box-body table-responsive no-padding">
						<table id="table_last_transaction" class="table  table-bordered table-hover table-striped">
							<thead>
								<tr class="tableheader">
									<th style="width:30px">#</th>
									<th style="width:87px">Date</th>
									<th style="width:87px">Id Trx</th>
									<th style="width:100px">Total</th>
									<th style="width:80px">Cashier</th>
									<th style="width:px"></th>
								</tr>
							</thead>
							<tbody></tbody>
						</table>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				</div>
				<!--modal footer-->
			</div>
			<!--modal-content-->
		</div>
		<!--modal-dialog modal-lg-->
	</div>

	<div id="passwordmodal" class="modal fade ">
		<div class="modal-dialog modal-md">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">×</button>
					<h4 class="modal-title">Password</h4>
				</div>
				<!--modal header-->
				<div class="modal-body">
					<div class="form-horizontal">
						<div class="box-body">
							<div class="form-group">
								<label class="col-sm-12" control-label "=" "><span id="ketpassword ">Type password before edit transaction</span></label>  </div><div class="form-group ">   <label class="col-sm-12 " control-label"="">
								<input type="password" class="form-control " id="txtpass" name="txtpass"  >
								<input type="hidden" id="txthidetrxid"   >
								<input type="hidden" id="txthiddentrans"   >
							</label>
						</div>
						<div class="form-group">
							<label class="col-sm-2  control-label">
								<button type="submit" class="btn btn-primary " id="btncheckpass" name="btncheckpass"><i class="fa  fa-lock"></i> Authentication</button> <span id="infopassword"></span>
							</label>
							<div class="col-sm-10"> </div>
						</div>
					</div>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
			</div>
			<!--modal footer-->
		</div>
		<!--modal-content-->
	</div>
	<!--modal-dialog modal-lg-->
</div>

<?php include "../layout/footer.php"; //footer template ?> 
<?php include "../layout/bottom-footer.php"; //footer template ?> 
<script src="../../plugins/datepicker/bootstrap-datepicker.js"></script>
<script src="../../dist/js/redirect.js"></script>
<script src="j_pos.js"></script>
</body>
</html>

Display the front end of the sales menu as shown below.

Point Of Sale With Php Front End Tutorial Create Pos Php

j_pos.js

$(document).ready( function () 
{
	$('#txtsalesdate,#txtfirstperiod,#txtlastperiod').datepicker({
		format: 'dd-mm-yyyy',
	});

	function reposition() {
		var modal = $(this),
		dialog = modal.find('.modal-dialog');
		modal.css('display', 'block');
		dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
	}

	$('.modal').on('show.bs.modal', reposition);
	$(window).on('resize', function() {
		$('.modal:visible').each(reposition);
	});

	$( "#modaleditparam" ).find( ".modal-footer" ).remove();
	$( "#modalpayment" ).find( ".modal-footer" ).remove();
	decimal();
	money();
	init_data();
	$( "#txtsearchitem" ).autocomplete({
		search  : function(){$(this).addClass('working');},
		open    : function(){$(this).removeClass('working');},
		source: function(request, response) {
			$.getJSON("autocomplete_item.php", { term: $('#txtsearchitem').val() }, 
				response); },
			minLength:1,
			select:function(event, ui){
				temptabel(ui.item.id_item);
			}
		}).autocomplete( "instance" )._renderItem = function( ul, item ) {
		return $( "<li>" )
		.append( "<dl><dt>"+item.label + "</dt>"+item.price+item.note+ "</dl>"  )
		.appendTo( ul );
	};
});

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

	var trx = $("#txthiddentrans").val();
	var id_sales = $("#txthidetrxid").val();
	if(id_sales == '' || id_sales == null)
	{
		$.notify({
			message: "No transaction processed"
		},{
			type: 'warning',
			delay: 5000,
		});
		return;
	}
	var pass=$("#txtpass").val();
	var value = {
		pass : pass,
		method : "check_password"
	};
	$.ajax(
	{
		url : "../model/check_password.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			if(data.auth == true)
			{
				$("#passwordmodal").modal("hide");
				$("#txtpass").val("");
				delete_trans(id_sales);
			}else{
				$.notify({
					message: "Password does not match"
				},{
					type: 'danger',
					delay: 10000,
				});
				set_focus("#txtpass");
				return;
			}
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			loading_stop();
		}
	});


});
function delete_trans(sale_id)
{
	var value = {
		sale_id : sale_id,
		method : "delete_trans"
	};
	loading_start();
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{

			var data = jQuery.parseJSON(data);
			if(data.result == true)
			{
				$("#btnfiltersale").click();
			}else{
				$.notify({
					message: "Error delete transaction , Error : "+data.error
				},{
					type: 'danger',
					delay: 10000,
				});
			}	
			loading_stop();
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			loading_stop();
			
		}
	});	
}
$(document).on("click",".btndeletesale",function(){
	$("#passwordmodal").modal("show");
	$("#txthidetrxid").val($(this).attr("sale_id"));
	$("#txthiddentrans").val("D");
	$("#notepassword").html("Please enter user password to delete transaction!");
	set_focus("#txtpass");
});

$(document).on("click","#btnpayment",function(){
	var id_trans = $("#txtidsales").val();
	var tgl_trans = $("#txtsalesdate").val();

	if(id_trans == '' || id_trans == null){
		$.notify({
			message: "Please fill out id transaction!"
		},{
			type: 'warning',
			delay: 10000,
		});	
		return;
	}
	if(tgl_trans == '' || tgl_trans == null){
		$.notify({
			message: "Please fill out transaction date!"
		},{
			type: 'warning',
			delay: 10000,
		});	
		return;
	}
	var value = {
		method : "check_tempsale"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			if(data.tempsale == false)
			{
				$.notify({
					message: "No items have been selected in the shopping cart list!"
				},{
					type: 'warning',
					delay: 10000,
				});	
				set_focus("#txtsearchitem");
				return;
			}else
			{
				var total = parseInt(cleanString($("#txttotal").html()));
				$("#txtinfoidtrans").val($("#txtidsales").val());
				$("#txtinfodatetrans").val($("#txtsalesdate").val());
				$("#txtgrandtotal").val(addCommas(total));
				$("#txtmoneypay").val(addCommas(total));
				$("#txtoddmoney").val(0);
				$("#modalpayment").modal("show");
				set_focus("#txtmoneypay");
			}
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			
		}
	});

})

$(document).on("blur","#txtmoneypay",function (){
	var total = parseInt(cleanString($("#txttotal").html()));
	var paid =  parseInt(cleanString($(this).val()));
	var returnchange = paid - total;
	if(isNaN(returnchange))
	{
		returnchange = 0;
		$("#txtmoneypay").val(addCommas(total));
	}
	if(paid < total){
		$("#txtmoneypay").val(addCommas(total));
		$("#txtoddmoney").val(0);
	}else{
		$("#txtoddmoney").val(addCommas(returnchange));
	}
});

$(document).on("click","#btnsavetrans",function()
{
	var sale_id = $("#txtidsales").val();
	var sale_date = $("#txtsalesdate").val();
	var paid =  parseInt(cleanString($("#txtmoneypay").val()));
	var disc_prcn = parseFloat(cleanString($("#txttotaldiscprc").val())); 
	var disc_rp = parseInt(cleanString($("#txttotaldiscrp").val()));
	var note= $("#txtnote").val();
	
	swal({   
		title: "Payment",   
		text: "Save payment ?",   
		type: "warning",   
		showCancelButton: true,   
		confirmButtonColor: "#DD6B55",   
		confirmButtonText: "Purchase",   
		closeOnConfirm: true }, 
		function(){   
			$("#btnsavetrans").prop('disabled', true);
			proccess_waiting("#infoproccesspayment");
			var value = {
				sale_id : sale_id,
				sale_date : sale_date,
				paid : paid,
				disc_prcn : disc_prcn,
				disc_rp : disc_rp,
				note : note,
				method : "save_trans"
			};
			$.ajax(
			{
				url : "c_pos.php",
				type: "POST",
				data : value,
				success: function(data, textStatus, jqXHR)
				{
					$("#btnsavetrans").prop('disabled', false);
					$("#infoproccesspayment").html("");
					var data = jQuery.parseJSON(data);
					if(data.result == true){
						var xid_sales = data.xid_sales;
						$("#modalpayment").modal('hide');
							setTimeout(function() {
							$.redirect("nota_jual.php",{ id_sales: xid_sales,duplikasi:0},'POST','_blank'); }, 500); // After 420 ms
						
						reset_data();
					}else{
						$.notify({
							message: "Error save transaction, error :"+data.error
						},{
							type: 'danger',
							delay: 10000,
						});		
					}

				},
				error: function(jqXHR, textStatus, errorThrown)
				{
					$("#infoproccesspayment").html("");
					$("#btnsavetrans").prop('disabled', false);
				}
			});
		});

})

$(document).on("click",".btndiscprc",function (e){
	e.preventDefault();
	$("#txttotaldiscprc").prop('disabled', false);
	$("#txttotaldiscrp").prop('disabled', true);
	$("#txttotaldiscprc").focus();
});
$(document).on("click",".btndiscrp",function (e){
	e.preventDefault();
	$("#txttotaldiscrp").prop('disabled', false);
	$("#txttotaldiscprc").prop('disabled', true);
	$("#txttotaldiscrp").focus();
});
$(document).on("blur","#txttotaldiscprc",function(){
	if (isNaN($(this).val()))
	{
		$(this).val(0);
	}
	if($(this).val() > 100 || $(this).val() < 0 ){
		$(this).val(0);
		var prcn = 0;
	}else{
		var prcn = parseFloat($(this).val());
	}
	var subtotal = parseInt(cleanString($("#txtsubtotal").val()));
	var discrp = subtotal * (prcn/100);
	var total = subtotal - discrp;
	$("#txttotaldiscrp").val(addCommas(discrp));
	$("#txttotal").html(addCommas(total)); 
});

$(document).on("blur","#txttotaldiscrp",function(){
	var subtotal = parseInt(cleanString($("#txtsubtotal").val()));
	if(parseInt(cleanString($(this).val())) > subtotal || parseInt(cleanString($(this).val())) < 0 ){
		$(this).val(0);
		var discrp = 0;
	}else{
		var discrp = parseInt(cleanString($(this).val()));
	}
	var prcn = (discrp/subtotal) * 100;
	if(isNaN(prcn)){
		prcn = 0;
	}
	if(isNaN(discrp)){
		discrp = 0;
	}
	var total = subtotal - discrp;

	$("#txttotaldiscprc").val(prcn.toFixed(2));
	$("#txttotal").html(addCommas(total)); 
});



$(document).on("click","#btnubahedit",function(){
	var nilai = cleanString($("#txtvalue").val());
	var jenis = $("#txtdataparam").val();
	var key = $("#txtkey").val();

	var value = {
		nilai: nilai,
		jenis:jenis,
		key:key,
		method : "updatedetail"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			if(data.result ==1){
				var table = $('#table_transaction').DataTable(); 
				table.ajax.reload( null, false );
				$( "#modaleditparam" ).modal("hide");
				refresh_total();
			}else{
				$.notify({
					message: "Error edit , error :"+data.error
				},{
					type: 'danger',
					delay: 10000,
				});		
			}

		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			
		}
	});
});
$(document).on("click",".btndelete",function(){
	var id_item = $(this).attr("id_item");
	var value = {
		id_item: id_item,
		method : "deletedetail"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			if(data.result ==1){
				var table = $('#table_transaction').DataTable(); 
				table.ajax.reload( null, false );
				refresh_total();
			}else{
				$.notify({
					message: "Error delete list item , error :"+data.error
				},{
					type: 'danger',
					delay: 10000,
				});		
			}

		},
		error: function(jqXHR, textStatus, errorThrown)
		{
		}
	});
});

$(document).on("click",".editparam",function(){
	var dataparam=$(this).attr("dataparam");
	var datatitle=$(this).attr("datatitle");
	var val=$(this).attr("val");
	var key = $(this).attr("key");

	$( "#modaleditparam" ).find( ".modal-title" ).html(datatitle);
	$("#txtdataparam").val(dataparam);
	$("#txtvalue").val(val);
	$("#txtkey").val(key)

	$("#modaleditparam").modal("show");
	set_focus("#txtvalue");


})
$(document).on("click",".btnnota",function(){
	var idjual = $(this).attr("id_sales");
	var jnsjual = $(this).attr("jns_jual");
	if(jnsjual == 1)
	{
		$.redirect("nota_jual.php",{ id_sales: idjual,duplikasi:1},'POST','_blank');
	}else{
		$.redirect("nota_tempo.php",{ id_sales: idjual,duplikasi:1},'POST','_blank'); 

	}
});

$(document).on("click","#btncancel",function(){
	swal({   
		title: "Reset",   
		text: "Empty transaction ?",   
		type: "warning",   
		showCancelButton: true,   
		confirmButtonColor: "#DD6B55",   
		confirmButtonText: "Reset",   
		closeOnConfirm: true }, 
		function(){   
			reset_data();
		});
});

function temptabel(idbrg){
	var value = {
		id_item: idbrg,
		method : "save_temptable"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			if(data.result ==1){
				var table = $('#table_transaction').DataTable(); 
				table.ajax.reload( null, false );
				$("#txtsearchitem").val("");
				refresh_total();
				set_focus("#txtsearchitem");
			}else{
				$.notify({
					message: "Error save item , error :"+data.error
				},{
					type: 'danger',
					delay: 10000,
				});		
			}

		},
		error: function(jqXHR, textStatus, errorThrown)
		{
		}
	});
}
function refresh_total(){
	var value = {
		method : "get_subtotal"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			var subtotal = data.subtotal;
			$("#txtsubtotal").val(addCommas(subtotal));
			$("#txttotaldiscprc").blur();
			var discrp = cleanString($("#txttotaldiscrp").val());
			var total =addCommas(subtotal - discrp);
			$("#txttotal").html(total);
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
		}
	});
	
}
$(document).bind('keydown', 'f9', function(){
	$("#btnpayment").click();
});
function newkdtrans(){
	var tgl = $("#txtsalesdate").val();
	var thn = tgl.substr(8, 4);
	var bln = tgl.substr(3, 2);
	var dy = tgl.substr(0, 2);
	var _first = 'J';
	$("#txtidsales").val(_first+thn+bln+dy+'###');
}
function reset_data(){
	var value = {
		method : "reset_table"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			if(data.result ==1){
				var table = $('#table_transaction').DataTable(); 
				table.ajax.reload( null, false );
				$("#txttotaldiscprc").val(0);
				$("#txttotaldiscrp").val(0);
				$("#txtsubtotal").val(0);
				$("#txttotal").html("0");
				$("#txtnote").val("");
				refresh_total();
				set_focus("#txtsearchitem");
			}else{
				$.notify({
					message: "Can not reset data, error :"+data.error
				},{
					type: 'danger',
					delay: 10000,
				});		
			}
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
		}
	});
}

$(document).on("click","#btnopentransaction",function(){

	$("#modallasttrans").modal("show");
	$("#table_last_transaction tbody").html("");
});
$(document).on("click","#btnfiltersale",function(){
	var first = $("#txtfirstperiod").val();
	var last = $("#txtlastperiod").val();
	var value = {
		first : first,
		last : last,
		method : "get_trans_sale"
	};
	$.ajax(
	{
		url : "c_pos.php",
		type: "POST",
		data : value,
		success: function(data, textStatus, jqXHR)
		{
			var data = jQuery.parseJSON(data);
			$("#table_last_transaction tbody").html(data.hasil);
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			
		}
	});
});
function init_data(){

	var value = {
		method : "getdata"
	};
	$('#table_transaction').DataTable({
		"paging": false,
		"lengthChange": false,
		"searching": false,
		"ordering": false,
		"info": false,
		"responsive": true,
		"autoWidth": false,
		"pageLength": 50,
		"dom": '<"top"f>rtip',
		"columnDefs": [
		{ className: "textright", "targets": [ 3,4,5,6 ] }
		],
		"ajax": {
			"url": "c_pos.php",
			"type": "POST",
			"data":value,
		},
		"columns": [
		{ "data": "urutan" },
		{ "data": "id_item" },
		{ "data": "item_name" },
		{ "data": "price" },
		{ "data": "qty" },
		{ "data": "discprc" },
		{ "data": "subtotal" },
		{ "data": "button" },
		]
	});
	$("#txttotaldiscprc").val(0);
	$("#txttotaldiscrp").val(0);
	$("#txtsubtotal").val(0);
	$("#txttotal").html("0");
	refresh_total();
	set_focus("#txtsearchitem");
	newkdtrans();
}

c_pos.php

<?php
session_start();
require_ once ("../model /dbconn.php");
require_ once ("../model /pos.php");
function display_to_sql($date){
	return substr($date,6,4).'-'.substr($date,3,2).'-'.substr($date,0,2);
}
$method=$_POST['method'];
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
	$pos = new pos();
	$menu = $pos->getSubMenuById(6);
	$menu_log = $menu[1];

	if($method == 'get_subtotal'){
		$uniqid =  $_SESSION['pos_uniqid'];
		$kasir =  $_SESSION['pos_id'];
		$pos = new pos();
		$array = $pos->getSubTotalTempSale($kasir,$uniqid);
		$result = array();
		$result['result'] = $array[0];
		$result['subtotal']=(int)$array[1];
		echo json_encode($result);
	}
if($method == 'get_trans_sale')
	{
		$first = display_to_sql($_POST['first']);
		$last	= display_to_sql($_POST['last']);
		$pos = new pos();
		$array = $pos->getTransSale($first,$last);
		$html='';
		$result = array();
		if($array[0] == true)
		{
			$i=1;
			foreach ($array[1] as $key) {

				if($key['sts']== 0)
				{
					$html .= '<tr class="strikeout">';
					$btn = 'delete';
				}else
				{
					$html .= '<tr >';
					$btn =  '<button  type="submit" sale_id="'.$key['sale_id'].'"  title="Delete Transaction" class="btn btn-danger btn-sm btndeletesale "  id="btndeletesale'.$key['sale_id'].'" name=""  ><i class="fa fa-remove"></i></button>';
				}
				$html .= '	<td class="tdstrike">'.$i.'</td>
				<td class="tdstrike">'.date('d/m/Y',strtotime($key['sale_date'])).'</td>
				<td class="tdstrike">'.$key['sale_id'].'</td>
				<td  class="tdstrike" style="text-align:right">Rp. '.number_format($key['total']).'</td>
				<td class="tdstrike">'.$key['username'].'</td>
				<td class="tdstrike" style="min-width:80px">'.$btn.'</td>
				</tr>';
				$i++;
			}
			$result['hasil'] = $html;
		}
		echo json_encode($result);
	}

	if($method == 'check_tempsale'){
		$uniqid =  $_SESSION['pos_uniqid'];
		$kasir =  $_SESSION['pos_id'];
		$pos = new pos();
		$array = $pos->getSubTotalTempSale($kasir,$uniqid);
		$result = array();
		$hasil = $array[1];
		if($hasil >=1){
			$result['tempsale']=true;		
		}else
		{
			$result['tempsale']=false;
		}
		echo json_encode($result);
	}
if($method == 'save_trans')
	{
		$sale_id = substr($_POST['sale_id'],0,7);
		$sale_date = display_to_sql($_POST['sale_date']);
		$paid =  $_POST['paid'];;
		$disc_prcn = $_POST['disc_prcn']; 
		$disc_rp = $_POST['disc_rp'];
		$note =  $_POST['note'];
		$uniqid =  $_SESSION['pos_uniqid'];
		$id_user =  $_SESSION['pos_id'];
		$pos = new pos();

		$insert = $pos->saveSale($sale_id, $sale_date,$paid,$disc_prcn,$disc_rp,$uniqid,$id_user,$note);
		$retval['result'] = $insert[0];
		$retval['error'] = $insert[1];
		$retval['xsale_id'] = $insert[2];

		echo json_encode($retval);
	}

if($method == 'save_temptable')
	{
		$uniqid =  $_SESSION['pos_uniqid'];
		$kasir =  $_SESSION['pos_id'];
		$id_item = $_POST['id_item'];
		$pos = new pos();
		$result = array();
		$query = $pos->getItem($id_item);
		$data = $query[1];
		$result['id_item'] = $data['id_item'];
		$result['item_name'] = $data['item_name'];
		$result['qty'] = 1;
		$result['unit'] = $data['unit'];
		$result['price'] = $data['price'];
		$result['discprcn'] = 0;
		$result['discrp'] = 0;

		$check = $pos->getCheckProduk($kasir,$uniqid,$result['id_item']);
		$jum = $check[1];

		if($jum >=1)
		{
			$update = $pos->updateTempSale($kasir,$uniqid,$result['id_item']);
			$retval['result'] = $update[0];
			$retval['error'] = $update[1];
		}
		else
		{
			$insert = $pos->saveTempSale($kasir,$uniqid,$result['id_item'],$result['unit'],$result['item_name'],$result['qty'], $result['price'], $result['discprcn'],$result['discrp']);
			$retval['result'] = $insert[0];
			$retval['error'] = $insert[1];
		}
		echo json_encode($retval);
	}
if($method == 'reset_table'){
		$uniqid =  $_SESSION['pos_uniqid'];
		$iduser =  $_SESSION['pos_id'];
		$pos = new pos();
		$reset = $pos->resetTempSaleByUserSession($iduser,$uniqid);
		$retval['result'] = $reset[0];
		$retval['error'] = $reset[1];
		echo json_encode($retval);
	}

	if($method == 'deletedetail'){

		$id_item = $_POST['id_item'];
		$uniqid =  $_SESSION['pos_uniqid'];
		$kasir =  $_SESSION['pos_id'];
		$pos = new pos();
		$delete = $pos->deleteTempSaleProduct($kasir,$uniqid,$id_item);
		$retval['result'] = $delete[0];
		$retval['error'] = $delete[1];
		echo json_encode($retval);
	}
	
if($method == 'updatedetail'){
		$value=$_POST['nilai'];
		$jenis = $_POST['jenis'];
		$uniqid =  $_SESSION['pos_uniqid'];
		$kasir =  $_SESSION['pos_id'];
		$pos = new pos();
		$key = explode('|', base64 _decode($_POST['key']));
		$id_item = $key[0];
		$unit = $key[1];
		if($jenis == 'hargajual')
		{
			$update = $pos->updateTempSaleHargaSale($kasir,$uniqid,$id_item ,$value);
		}
		else if($jenis == 'qty')
		{
			$update = $pos->updateTempSaleQty($kasir,$uniqid,$id_item ,$value);
		}
		else if($jenis == 'disc')
		{
			$update = $pos->updateTempSaleDisc($kasir,$uniqid,$id_item ,$value);
		}
		else
		{
			echo 'error';
		}
		$retval['result'] = $update[0];
		$retval['error'] = $update[1];
		echo json_encode($retval);
	}
	if($method == 'getdata' ){
		$uniqid =  $_SESSION['pos_uniqid'];
		$kasir =  $_SESSION['pos_id'];
		$pos = new pos();
		$array = $pos->getListTempSale($kasir,$uniqid);
		$data = $array[1];
		$i=0;
		foreach ($data as $key) {
			$keys = $key['id_item'].'|'.$key['unit'];
			$keys = base64_encode($keys);
			$total = ($key['price'] - ($key['price'] * $key['discprc'] /100) ) * $key['qty'] ;
			$data[$i]['price'] = '<a href="#" class="editparam" key="'.$keys.'"  datatitle="Harga Sale" dataparam="hargajual" val="'.number_format($key['price']).'">'.number_format($key['price']).'</a>';		
			$data[$i]['qty'] = '<a href="#" class="editparam" key="'.$keys.'" datatitle="Qty" dataparam="qty" val="'.number_format($key['qty']).'">'.number_format($key['qty']).' '.$key['unit'].'</a>';
			$data[$i]['discprc'] = '<a href="#" class="editparam" key="'.$keys.'" datatitle="Discount" dataparam="disc" val="'.number_format($key['discprc'],2).'">'.number_format($key['discprc'],2).'</a>';

			$data[$i]['subtotal'] = '<span class="csubtotal">'.number_format($total)."</span>";
			$data[$i]['button'] = '<button  type="submit" id_item="'.$key['id_item'].'" unit="'.$key['unit'].'"   class="btn btn-primary btndelete btn-sm"  id="btndeletes'.$key['id_item'].'"   ><i class="fa fa-remove"></i></button>';
			$i++;
		}
		$datax = array('data' => $data);
		echo json_encode($datax);
	}

	if($method == 'delete_trans')
	{
		$sale_id = $_POST['sale_id'];
		$username = $_SESSION['pos_username'];
		$notehapus = 'Deleted by : '.$username.' ,at : '.date("l jS \of F Y h:i:s A");
		$pos = new pos();
		$array = $pos->deleteSale($sale_id,$notehapus);
		$data['result'] = $array[0];
		$data['error'] = $array[1];
		echo json_encode($data);
	}

} else {
	exit('No direct access allowed.');
}
?>

And add the following code in the pos.php file

public function deleteTempSaleByUser($iduser)
   {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("delete from temp_sale where id_user = :id");
      $stmt->bindParam("id",$iduser);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Success Delete!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }
  public function resetTempSaleByUserSession($iduser,$uniqid)
  {
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("delete from temp_sale where id_user = :id and uniqid = :uniqid");
      $stmt->bindParam("id",$iduser);
      $stmt->bindParam("uniqid",$uniqid);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = "Success Delete!";
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }
  public function getListTempSale($cashier,$uniqid){
    $db = $this->dblocal;
    try
    {
      $stmt = $db->prepare("SELECT @rownum := @rownum + 1 AS urutan,t.*
        FROM temp_sale t, 
        (SELECT @rownum := 0) r where t.id_user= :cashier and t.uniqid= :uniqid  ORDER BY input_date ASC");
      $stmt->bindParam("cashier",$cashier);
      $stmt->bindParam("uniqid",$uniqid);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
      return $stat;
    }
    catch(PDOException $ex)
    {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }


  public function deleteTempSaleProduct($cashier,$uniqid,$id_item)
  {
   $db = $this->dblocal;
   try
   {
    $stmt = $db->prepare("delete from temp_sale where id_user = :id and uniqid = :uniqid and id_item = :id_item ");
    $stmt->bindParam("id",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Success Delete!";
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}

public function updateTempSale($cashier,$uniqid,$id_item)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("update temp_sale set qty=qty+1 where uniqid= :uniqid and id_user = :cashier 
      and id_item = :id_item ");

    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);

    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Success Edit!";
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function updateTempSaleHargaSale($cashier,$uniqid,$id_item,$value)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("update temp_sale set price = :value
      where uniqid= :uniqid and id_user = :cashier 
      and id_item = :id_item ");

    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);
    $stmt->bindParam("value",$value);

    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Sukses Ubah!";
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function updateTempSaleQty($cashier,$uniqid,$id_item ,$value)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("update temp_sale set qty= :value where uniqid= :uniqid and id_user = :cashier 
      and id_item = :id_item ");

    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);
    $stmt->bindParam("value",$value);

    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Success Edit!";
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function deleteSale($sale_id,$note)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("call deleteSale(:id,:note)");
    $stmt->bindParam("id",$sale_id);
    $stmt->bindParam("note",$note);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = 'Success Delete';
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function updateTempSaleDisc($cashier,$uniqid,$id_item,$value)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("update temp_sale set discprc = :value
      where uniqid= :uniqid and id_user = :cashier 
      and id_item = :id_item ");

    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);
    $stmt->bindParam("value",$value);

    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Success Edit!";
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}

public function saveTempSale($cashier,$uniqid,$id_item,$unit,$item_name,$qty,$price,$discprn,$discrp)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("insert into temp_sale(id_user, uniqid, id_item, item_name, qty, unit, price, discprc, discrp) values 
      (:cashier , :uniqid , :id_item, :item_name, :qty, :unit, :price, :discprn, :discrp)");
    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);
    $stmt->bindParam("unit",$unit);
    $stmt->bindParam("item_name",$item_name);
    $stmt->bindParam("qty",$qty);
    $stmt->bindParam("price",$price);
    $stmt->bindParam("discprn",$discprn);
    $stmt->bindParam("discrp",$discrp);

    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Success save!";
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function saveSale($sale_id,$sale_date,$paid,$disc_prcn,$disc_rp,$uniqid,$id_user,$note)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("call saveSale( :sale_id, :sale_date, :paid, :disc_prcn,
     :disc_rp, :uniqid, :id_user, :note)");
    $stmt->bindParam("sale_id",$sale_id);
    $stmt->bindParam("sale_date",$sale_date);
    $stmt->bindParam("paid",$paid);
    $stmt->bindParam("disc_prcn",$disc_prcn);
    $stmt->bindParam("disc_rp",$disc_rp);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_user",$id_user);
    $stmt->bindParam("note",$note);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = "Success Save!";
    $stat[2] =  $stmt->fetchColumn(0);
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function getSubTotalTempSale($cashier,$uniqid){
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("SELECT SUM((price - (price*(discprc/100)))*qty)AS total 
      FROM temp_sale where uniqid= :uniqid and id_user = :cashier");
    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = $stmt->fetchColumn(0);
    $stat[2] = $stmt->rowCount();
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}
public function checkTempSale($cashier,$uniqid){
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("SELECT id_user,uniqid FROM temp_sale where uniqid= :uniqid and id_user = :cashier");
    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = $stmt->rowCount();
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}

public function getCheckProduk($cashier,$uniqid,$id_item ){
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("select * from temp_sale where uniqid= :uniqid and id_user = :cashier and id_item = :id_item");
    $stmt->bindParam("cashier",$cashier);
    $stmt->bindParam("uniqid",$uniqid);
    $stmt->bindParam("id_item",$id_item);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = $stmt->rowCount();
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}


public function getTransSale($awal,$akhir,$order = 'desc')
{
 $db = $this->dblocal;
 try
 {
  $stmt = $db->prepare("SELECT  a.`sale_date`,a.`sale_id`,
    (SELECT SUM((d.price - (d.price*(d.disc_prc/100)))*d.qty) AS total
    FROM t_sale_detail d WHERE d.sale_id = a.sale_id)AS total,
    c.`username`,a.sts,a.paid,a.disc_rp
    FROM t_sale a 
    INNER JOIN m_user c ON a.`id_user` = c.`id_user`
    where (a.`sale_date` BETWEEN :awal AND :akhir)
    ORDER BY sale_id ".$order );
  $stmt->bindParam("awal",$awal);
  $stmt->bindParam("akhir",$akhir);
  $stmt->execute();
  $stat[0] = true;
  $stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
  return $stat;
}
catch(PDOException $ex)
{
  $stat[0] = false;
  $stat[1] = $ex->getMessage();
  return $stat;
}
}


public function getSaleId($id){
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("SELECT a.* ,c.`username`
      FROM t_sale a 
      INNER JOIN m_user c ON a.`id_user` = c.`id_user` where a.sale_id = :id");
    $stmt->bindParam("id",$id);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = $stmt->fetch(PDO::FETCH_ASSOC);
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}

public function getSaleDetailIdSale($id)
{
  $db = $this->dblocal;
  try
  {
    $stmt = $db->prepare("SELECT @rownum := @rownum + 1 AS urutan, a.*,
      (a.price - ((a.price * a.disc_prc) /100) ) * a.qty as total 
      from t_sale_detail a,(SELECT @rownum := 0) r  where a.sale_id = :id");
    $stmt->bindParam("id",$id);
    $stmt->execute();
    $stat[0] = true;
    $stat[1] = $stmt->fetchall(PDO::FETCH_ASSOC);
    return $stat;
  }
  catch(PDOException $ex)
  {
    $stat[0] = false;
    $stat[1] = $ex->getMessage();
    return $stat;
  }
}

Up to this point, the tutorial how to create a point of sale system with PHP, PDO, jquery and adminLTE has been completed. A brief explanation on the sales transaction page:

To add an item to the shopping cart grid, we use the jquery UI autocomplete. By typing the item name or item code in the text box field, jquery will display a list of items like the following picture

Autocomplete Item On Point Of Sale System Tutorial Build Point Of Sale In Php Pdo Jquery And Adminlte

Jquery ajax will call autocomplete function in autocomplete_item.php file

To add the number of items, the user can click on the item qty section and will display the modal dialog to change qty.

If the user selects the same item in the autocomplete box, it will automatically add qty item to the grid.

Add Item In Shoping Cart Grid Tutorial Pos With Php

process payment button will display the transaction payment modal dialog like the following picture:

Point Of Sale Layout Template

After the transaction has been processed, jquery will execute the redirect script to display the sales receipt on the new browser tab (in PDF format). For the tutorial create sales receipt with PDF, I will discuss in the bonus article

Javascript redirect is useful to replace form element in HTML. This script is very useful for me to send data using POST method without creating form element in HTML.

DONE!! The tutorial point of sale system with PHP has been completed. In accordance with my promise from the beginning, you can download the complete source code of this project on the download link below:

I hope this article is helpful for all of us. If you feel helped by this article, Please give me a donation or a gift. To keep me excited about creating articles. ;p

Thus tutorial about How To Create a Sales Form / POS – Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 5

[Resolved] SweetAlert Prompt Not Working On Modal Dialog Bootstrap In Firefox

$
0
0

Have you ever experienced a sweetalert prompt box function blank or input box disabled when invoked via the bootstrap modal dialog on Mozilla firefox browser? I experienced it. So far I use chrome browser to test my application and runs well. When my client asks for an error on the application when calling the sweetalert prompt dialog box function, I just found out if there is an error in the plugin sweetalert prompt dialog box on modal dialog bootstrap in firefox browser.

Here An Image of sweetalert prompt box that is disabled when invoked via modal dialog bootstrap on Mozilla firefox:

Sweetalert Crash With Modal Dialog Bootstrap In Mozilla Firefox

This “enforceFocus” issue has been discussed on some GitHub and stackoverflow.com as follows:

The problem I faced is most likely due to the use of multiple bootstrap modal dialogs that makes the sweetalert plugin not work properly in firefox browser

How to problem solve crash at the sweetalert prompt box in firefox by adding 1 line script to “override enforceFocus” in modal dialog bootstrap. Please add the following script after the sweetalert plugin js is loaded.

$.fn.modal.Constructor.prototype.enforceFocus = function() {};

I do not know what makes a sweetalert plugin crash with bootstrap modal dialog box on firefox, but with a line above the sweet alert prompt box runs well when invoking via bootstrap modal dialog on Mozilla firefox as shown below.

Sweetalert Plugin Run Well After Insert Enforcefocus Script

I once discussed about the sweetalert plugin on some of my articles:

Thus my short article about [Resolved] SweetAlert Prompt Not Working On Modal Dialog Bootstrap In Firefox

How To Centering And Make Full Width Youtube Iframe On Blog Article

$
0
0

Adding content youtube into post articles often make us hassle to show the youtube video at the center position. By adding youtube content into articles can improve your website SEO ranking. But often the youtube iframe can’t appear in the right position so the embed video display becomes unattractive. Maybe you are a new blogger and do not understand about CSS feel frustrated when you want to put the video on your WordPress site.

The look of the standard embedded youtube video in WordPress article like the following picture:

How To Centering And Make Full Width Youtube Iframe On Blog Article

The image above shows that the youtube video I embed are not in the middle position and looks unattractive layout. I will share a short trick to help you in setting the video embed position to be in the middle of your article content.

Putting a Youtube Embed Video In Center Position

After getting the youtube embed code, add the div element to wrap the youtube iframe code like this:

<div style="text-align: center;">Your youtube embed code</div>

And the result of the installation of the above code makes the video in the right position now, that is in the middle. You can’t center the video by clicking the “align center” format button on the WordPress “visual editor” tab but still have to add the div element code using the manual on the “text editor” tab. And the results become as shown below.

Thus you have successfully created a video embed youtube right in the middle position

Installing Video Embed Youtube Full Width

To install video embed youtube for the full width you need to add a little CSS to set youtube iframe. This trick I get directly from the site css-tricks.com. Here’s how:

You should add this CSS code via the “Text editor” tab. Then add the following CSS code:

Wrap the embed youtube code with the div element as follows

<div class="videoWrapper">
Your youtube embed code
</div>

Here the result:

In addition to the above, there is an easier manual way: by choosing the custom width and height iframe on the youtube option menu like the following image:

Make Full Width Youtube Iframe Video On Blog Article WordPress

If you want to add an entire youtube video to your old article, you can add a jquery script to execute a youtube embed video on every article. You can read the tips here https://css-tricks.com/fluid-width-youtube-videos/

Above is a way to install embed video in center position and set the full width video on WordPress, hopefully this simple article useful.

How To Avoid Google Fred Update With Play Fair SEO

$
0
0

How is your website traffic since the beginning of March 2017? I’m sure you feel strange with traffic that goes up and down in early March 2017. This is because Google has just launched a new algorithm called fred algorithm. Fred algorithm is a system designed by google with its predecessor algorithm combination. In this article, I will share a bit about how to avoid google fred update with play fair SEO.

A lot of website traffic is uprooted because of the fred algorithm so the bloggers wonder what is being targeted by google using the fred algorithm. As one of the world’s largest search engine today, Google would like to satisfy users with search results that are relevant and as expected by the user.

What is google fred algorithm?

Although there is no official certainty from google regarding fred algorithms, but SEO experts believe Google fred  update is targeted at websites link building. Both internal links and external links. There are two possibilities in this fred algorithm regarding link building.

1. Backlink Spam Building

Be careful if you like to build backlinks with black hat method. What are the criteria of black hat method in building backlink?

  • Use the comment spam tool to paste the active link in targeting site.
  • Using dummy blogs or zombie blogs to build external link.
  • Buy backlinks from link building services including PBN services.

2. Related link

If you install widget related post make sure that article is relevant to your main post topic. This 2nd speculation does not seem to make sense, but who does not believe in SEO experts words.

Indeed there is no definite update of this fred algorithm, we are all still waiting for official information from google.

Luckily, since Fred algorithm rolled out by google, my website has not changed any traffic. You can see the following images:

How To Avoid Google Fred Update With Play Fair SEO

I’m not doing any weird tricks / black hat SEO to improve my website ranking. Some of the basic principles I do to avoid google fred update are:

  1. Create tutorial articles that are useful for visitors. The point is to make articles useful for your visitors, not for search engines.
  2. Improve communication with your visitors through the comments form, so that visitors feel at home on your site.
  3. No need to backlink spamming, if your posts are qualified automatically the visitors will share your articles with other users.
  4. Create original, interesting and unique articles, because “the content is king”.
  5. Do not shoot excessive keywords.
  6. Enrich articles or blog content by adding infographics, videos, and podcasts.

For those affected by fred, the most powerful way to improve traffic due to google Fred algorithm is to do disavow links against backlinks that are not quality (spamming backlinks). This method proved successful.

Thus my article about How to avoid google fred update with play fair SEO, hope useful 🙂

Check It Now Before Joining, Is Your Niche’s Blog Eligible For Google Adsense Product?

$
0
0

Niche is a topic that plays an important role in success as a blogger. Also, the right selection of niche also affects your site is eligible for AdSense or not. Even the acquisition of income from Adsense is also determined by the proper selection of niche because not all blog topics will generate the same passive income from AdSense.

Some topics do not fit with the AdSense program. Before you join the AdSense program, you must make correction back and make sure whether the niche you write into the blog is accordance with Google Adsense TOS. Do the following tips, so you do not waste time and give up how to earn passive income.

Read: Transfer Your Hobby To $1,000 Passive Income Every Month.

Some topics have a high click value, and some do not interest to advertisers. I am a beginner in AdSense program, but from some great blogs that I read some time ago, I summarize some of the niches you should avoid providing maximum results of your passive income.

Niche With Low Adsense income

Google Adsense Best Niche

A niche listing that has no potential when paired with Adsense programs

Political Niche

Political niche is seasonal. You will earn money during political competition or election. This niche competition level is also quite high, and most visitors prefer to visit big sites like CNN, BBC, FOXNEWS, etc.

In general, ads for this topic are tiny and little value, because there are no products sold to visitors.

Celebrities or Gossip Niche

It’s true this niche can bring in a lot of visitors because many fans want to know the news and gossip of her or his actresses. But almost no AdSense advertisers have the business related to celebrities. From the side of AdSense earnings, this niche is a small value.

To generate passive income from this niche, you must strive to increase your traffic as high as possible so that you will earn revenue from Adsense’s CPM.

Religion Niche

Rarely advertisers who advertise their religion through the AdSense program. Also, religious topics are always the pros and cons of many people. My advice if you focus on AdSense product, avoid this niche. Even in some countries, this niche causes legal problems.

Sports Niche

Almost similar to celebrity topics, low per-click values, and no high-value products related to sports moments. But it will be different if you have a niche of sports equipment. For example a tool for diet, an instrument to play golf. Look for a niche that has a high selling market.

Adult Niche

Google Adsense prohibits it

In addition to the selection of the above niche, there are often some things we do not realize that cause our blog doesn’t make eligible with Google AdSense program policies.

This needs to be considered if you are serious about implementing the Adsense program, so don’t wait for a warning report from Google, especially banned from Adsense.

Here are things that are not allowed by Google Adsense that you must understand

  • Selling imitation items. Avoid discussing and sharing information about replica items. Selling these replica items goes against the Adsense policy.
  • Gambling. I don’t need to explain this, Something related to crime is definitely violating the AdSense policy.
  • Weapons and ammunition. Selling weapons and accessories, Includes air gun, and firecracker sales.
  • Alcohol and liquor. That should not be selling and distributing liquor. Another case if you just review the taste and information about the liquor.
  • Cigarette and tobacco. Almost the same as alcohol and liquor.
  • Hacking / Cracking. Similar to gambling, this is certainly related to crime.
  • Adult content. Includes adult stories, pictures, sexual aids.
  • Drugs and equipment.
  • Racist and violent content.
  • Paid to surf / click / search. Be careful when giving information about PTC, this kind of program clearly violates Google Adsense policy.
  • Other illegal activities. Violence against children, pedophiles, including images, engineering videos depicting violence and deviant behavior toward children.
  • Excessive and irrelevant use of keywords. Important to understand, excessive use of keywords can interfere with the performance of Google search engine. Google highly dislikes this. In addition to Google, the article becomes unattractive to read. Read : Optimize Blog To Make Adsense Ads More Relevant With Your Content

More can be read on Adsense support page. Hopefully, after reading this article, understand and apply it, your passive income can be increased.

Thus my article about the blog niche that eligible for Google Adsense Product.

Viewing all 231 articles
Browse latest View live