Quantcast
Channel: The Code of a Ninja
Viewing all 100 articles
Browse latest View live

Loading Data Related To Selected Drop-Down Item Using PHP And jQuery

$
0
0
I used this code when I have a small list of records (e.g. authors or categories) that can be picked using a drop-down list and then, I want to load the related information instantly without refreshing the page. So in this post, we are going to code that does:
  • A drop down list with small number of names or authors
  • When a user selected an item from the drop down, it will load the related data below it.
Loading Data Related To Selected Drop-Down Item

Download code and live demo here:

download Loading Data Related To Selected Drop-Down Item example  Download PHP, jQuery onChange() and onLoad() Live Demo

We are going to use 4 files only, see below:

1. js/jquery-1.9.1.min.js - our favorite JavaScript library.

2. dbConnect.php - so that we can connect to the database users table

3. index.php - this will show the users drop-down list, records are from the database users table.

<html>
<head>
<title>CodeOfaNinja.com - Loading Data With PHP, jQuery onChange() and load()</title>
<style>
body{
font-family:arial,sans-serif;
}

select{
margin:0 0 10px 0;
padding:10px;
}

td {
background-color:#e8edff;
padding: 10px;
}
</style>
</head>
<body>

<?php
// connect to database
include"dbConnect.php";

// retrieve list of users and put it in the select box
$query="SELECT id, firstname, lastname, username FROM users";
$stmt=$con->prepare( $query );
$stmt->execute();

//this is how to get number of rows returned
$num=$stmt->rowCount();

// make sure there are records on the database
if($num>0){

// this will create selec box / dropdown list with user records
echo"<select id='users'>";

// make a default selection
echo"<option value='0'>Select a user...</option>";

while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo"<option value='{$id}'>{$firstname} {$lastname}</option>";
}
echo"</select>";

}

// if no user records
else{
echo"<div>No records found</div>";
}

// this is where the related info will be loaded
echo"<div id='userInfo'></div>";
?>

<scriptsrc="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("#users").change(function(){

// get the selected user's id
var id =$(this).find(":selected").val();

// load it in the userInfo div above
$('#userInfo').load('data.php?id='+ id);

});
});
</script>

</body>
</html>

4. data.php - this contains the query and will show the table with information related to the selected drop-down item.

<?php
include'dbConnect.php';

try {

// prepare query
$query="select
firstname, lastname, username
from
users
where
id = ?"
;

$stmt=$con->prepare( $query );

// this is the first question mark above
$stmt->bindParam(1, $_REQUEST['id']);

// execute our query
$stmt->execute();

// store retrieved row to a variable
$row=$stmt->fetch(PDO::FETCH_ASSOC);

// values to fill up our table
$firstname=$row['firstname'];
$lastname=$row['lastname'];
$username=$row['username'];

// our table
echo"<table>";
echo"<tr>";
echo"<td>Firstname: </td>";
echo"<td>{$firstname}</td>";
echo"</tr>";
echo"<tr>";
echo"<td>Lastname: </td>";
echo"<td>{$lastname}</td>";
echo"</tr>";
echo"<tr>";
echo"<td>Username: </td>";
echo"<td>{$username}</td>";
echo"</tr>";
echo"</table>";

}catch(PDOException$exception){

// to handle error
echo"Error: ".$exception->getMessage();
}
?>

You may have the sample MySQL table and data below:

CREATETABLEIF NOT EXISTS `users` (
`id`int(11) NOT NULL AUTO_INCREMENT,
`firstname`varchar(32) NOT NULL,
`lastname`varchar(32) NOT NULL,
`username`varchar(32) NOT NULL,
`password`varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `users`
--

INSERT INTO`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');

A Quick Way To Create A Vertical Accordion With jQuery

$
0
0
Today we are going to create a vertical accordion from scratch, using jQuery of course! We will have few lines of code that would be easy to understand. I used this code when I was asked to create an accordion for a website's headlines.

jquery accordion tutorial

So in this example code, we will have:

  • Three headlines, one headline is opened on load by default.
  • When a use clicks on a headline with hidden content, it will slide down the hidden content to be shown and close (slide up) the previously opened headline.
jquery accordion tutorial - code download  jquery accordion tutorial- live demo

CSS - You may do your tweaks to design your own accordion (change colors, add images, etc.) but make sure the main style are the following.

body {
font-family:Georgia, serif;
}

.headlineTitle {
font-weight:bold;
padding:5px0;
}

.item {
border:thinsolid#c0c0c0;;
margin:000.5em0;
}

.itemContents {
display:none;
margin:.05em000;
padding:10px;
}

.itemTitle {
background-color:#FAEBD7;
cursor:pointer;
font-weight:bold;
padding:10px;
}

.openedContent {
display:block;
}

HTML - Our html scructure would look like this. This could be generated multiple times by your server side script like PHP (reading records from a database), but in this example, we are using static HTML.

<divclass="itemsContainer">
<divclass="item">
<divclass="itemTitle opened">First Headline</div>
<divclass="itemContents openedContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
</div>
</div>
<divclass="item">
<divclass="itemTitle">Second Headline</div>
<divclass="itemContents">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
</div>
</div>
</div>

jQuery - makes our accordion work with few lines of codes.

$('.itemTitle').click(function () {

// show the content only if it is hidden
if ($(this).closest('.item').find('.itemContents').is(":hidden")) {

//open the content
$(this).closest('.item').find('.itemContents').slideDown("fast");

//close previously opened content
$(this).closest('.itemsContainer').find('.opened').closest('.item').find('.itemContents').slideUp("fast");

// remove the "opened" class from previously opened content
$(this).closest('.itemsContainer').find('.opened').removeClass('opened');

//add class to mark the clicked item is opened
$(this).addClass("opened");
}
});


Complete Page Code - Enjoy!

<!DOCTYPE HTML>
<html>
<head>
<title>jQuery Accordion</title>
<style>
body {
font-family:Georgia, serif;
}

.headlineTitle {
font-weight:bold;
padding:5px 0;
}

.item {
border:thin solid #c0c0c0;;
margin:0 0 0.5em 0;
}

.itemContents {
display:none;
margin:.05em 0 0 0;
padding:10px;
}

.itemTitle {
background-color:#FAEBD7;
cursor:pointer;
font-weight:bold;
padding:10px;
}

.openedContent {
display:block;
}
</style>
</head>

<body>

<divclass="itemsContainer">
<divclass="item">
<divclass="itemTitle opened">First Headline</div>
<divclass="itemContents openedContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
</div>
</div>
<divclass="item">
<divclass="itemTitle">Second Headline</div>
<divclass="itemContents">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
</div>
</div>
<divclass="item">
<divclass="itemTitle">Third Headline</div>
<divclass="itemContents">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
</div>
</div>
</div>

<scripttype='text/javascript'src="js/jquery-1.9.1.min.js"></script>
<scripttype='text/javascript'>
$(document).ready(function () {
$('.itemTitle').click(function () {

// show the content only if it is hidden
if ($(this).closest('.item').find('.itemContents').is(":hidden")) {

//open the content
$(this).closest('.item').find('.itemContents').slideDown("fast");

//close previously opened content
$(this).closest('.itemsContainer').find('.opened').closest('.item').find('.itemContents').slideUp("fast");

// remove the "opened" class from previously opened content
$(this).closest('.itemsContainer').find('.opened').removeClass('opened');

//add class to mark the clicked item is opened
$(this).addClass("opened");
}
});
});
</script>

</body>
</html>

How To Create A Basic PHP Login Script With PHP Sessions

$
0
0
Hi there! Today we are going to code one of the very basic requirement of a PHP web app - a PHP login script. This post also covers the log-out script. We are going to manage these tasks with the help of PHP sessions. A PHP session consists of a way to preserve certain data that can be used across different pages or section of your website.

PHP Login Script tutorial

Our code for today will do the following:

  • Show user a login form (login.php) and validate the inputs when the "Login" button was clicked. It will either say "Access Denied" if the login failed, or else, be redirected to the index page (main page of your web app, index.php).
  • When the user is not yet logged in and tried to go to the index page directly via pasting the URL, he will be redirected to the login page with a message "You cannot go to the index page because you are not yet logged in."
  • When the user is already logged in and tried to go to the login page, he will be redirected to the index page and tell him "You cannot go to login page because you are already logged in."
php login script code download  php login script live demo

login.php - will show the login form where the user can enter his username and password. Please note that we didn't use a database to get and match the entered username and password since we are just taking a look on how a PHP login script works. If you want to integrate this with a database, this is a nice start: PDO read records.

<?php
// STEP 1. Start the PHP session.
// should be the first to start, to prevent 'headers already sent' errors
session_start();

// STEP 2. Check if a user is logged in by checking the session value
if($_SESSION['logged_in']==true){

// if it is, redirect to index page and tell the user he's already logged in
header('Location: index.php?action=already_logged_in');
}
?>
<html>
<head>
<title>www.codeofaninja.com - php login script</title>
<linktype="text/css"rel="stylesheet"href="css/style.css" />
</head>
<body>

<divid="loginForm">

<?php
// STEP 3. Check for an action and show the approprite message.
if($_GET['action']=='not_yet_logged_in'){
echo"<div id='infoMesssage'>You cannot go to the index page because you are not yet logged in.</div>";
}

// STEP 4. Check if the user clicked the 'Login' button already by checking the PHP $_POST variable
if($_POST){

// these username and password are just examples, it should be from you database
// passwords must be encrypted (salt and hash) to be secured, my old post should give you an idea or see the update below
$username='subscriber';
$password='codeofaninja';

// check if the inputted username and password match
if($_POST['username']==$username&&$_POST['password']==$password){

// if it is, set the session value to true
$_SESSION['logged_in'] =true;

// and redirect to your site's admin or index page
header('Location: index.php');

}else{

// if it does not match, tell the user his access is denied.
echo"<div id='failedMessage'>Access denied. :(</div>";
}
}
?>

<!-- where the user will enter his username and password -->
<formaction="login.php"method="post">

<divid="formHeader">Admin Login</div>

<divid="formBody">
<divclass="formField">
<inputtype="text"name="username"placeholder="Username" />
</div>

<divclass="formField">
<inputtype="password"name="password"placeholder="Password" />
</div>

<div>
<inputtype="submit"value="Login"class="customButton" />
</div>
</div>

<divid="userNotes">
<div>Username: subscriber</div>
<div>Password: codeofaninja</div>
<div><ahref="index.php">Go to index page</a></div>
</div>
</form>

</div>

</body>
</html>

index.php - contains your main page, can be your admin page or the user dashboard. This will be shown when the user has successfully login to the system.

<?php
// STEP 1. Start the PHP session.
// should be the first to start, to prevent 'headers already sent' errors
session_start();

// STEP 2. Check if a user is NOT YET logged in by checking the session value
if(empty($_SESSION['logged_in'])){

// if the session value is empty, he is not yet logged in
// redirect him to login page
header('Location: login.php?action=not_yet_logged_in');
}
?>
<html>
<head>
<title>Sucessful Login</title>
<linktype="text/css"rel="stylesheet"href="css/style.css" />
</head>
<body>

<?php
// STEP 3. get and check the action
// action determines whether to logout or show the message that the user is already logged in

$action=$_GET['action'];

// executed when user clicked on "Logout?" link
if($action=='logout'){

// destroy session, it will remove ALL session settings
session_destroy();

//redirect to login page
header('Location: login.php');
}

else if($action=='already_logged_in'){
echo"<div id='infoMesssage'>You cannot go to login page because you are already logged in.</div>";
}
?>

<!-- some contents on our index page -->
<divid='successMessage'>You are logged in. :)</div>
<divid='actions'>
<ahref='index.php?action=logout'>Logout?</a> | <ahref='login.php'>Go to login page</a>
</div>

</body>
</html>

style.css - for our user interface. As for the message boxes, you can improve it by adding an icon or border such as the one I used here: Four message boxes with CSS.

body{
font:20px"Lucida Grande", Tahoma, Verdana, sans-serif;
color:#404040;
}

input[type=text],
input[type=password]{
padding:10px;
width:100%;
}

#userNotes{
font-size:0.7em;
text-align:left;
padding:10px;
}

#actions{
padding:10px;
}

#infoMesssage{
padding:10px;
background-color:#BDE5F8;
color:black;
font-size:0.8em;
}


#successMessage{
padding:10px;
background-color:green;
color:white;
}

#failedMessage{
padding:10px;
background-color:red;
color:white;
font-size:15px;
}

#formBody{
padding:5px;
}

#loginForm{

text-align:center;
border:thinsolid#000;
width:300px;
margin:7emauto0auto;
}

#formHeader{
border-bottom:thinsolidgray;
padding:10px;
background:#f3f3f3;
}

#loginForm{

}

.customButton {
padding:5px;
width:100%;
-moz-box-shadow:inset0px1px0px0px#bbdaf7;
-webkit-box-shadow:inset0px1px0px0px#bbdaf7;
box-shadow:inset0px1px0px0px#bbdaf7;
background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
background:-moz-linear-gradient( centertop, #79bbff5%, #378de5100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
background-color:#79bbff;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1pxsolid#84bbf3;
display:inline-block;
color:#ffffff;
font-family:arial;
font-size:15px;
font-weight:bold;
text-decoration:none;
text-shadow:1px1px0px#528ecc;
cursor:pointer;
}

.customButton:hover {
background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
background:-moz-linear-gradient( centertop, #378de55%, #79bbff100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
background-color:#378de5;
}

.customButton:active {
position:relative;
top:1px;
}
/* This imageless css button was generated by CSSButtonGenerator.com */

Update: As @ccornutt suggests in a comment below, I should emphasize something about how to hash and salt (not really encrypt) login passwords. If you're looking for a good tool for password hashing, check out this project: https://github.com/ircmaxell/password_compat (or, if you're on PHP 5.5+ you can just use the password_hash() function natively).

Android Bluetooth Code to Print Text on a Bluetooth Printer

$
0
0
Recently, I was asked to make a program for printing some data to a small or handheld Bluetooth printer device. This can be used for printing receipts, simple tickets, or customer notes. I like how it works because usually, we are getting our program output on a computer screen, but  this time we are getting our output on a tangible paper!

android bluetooth code example
Click to enlarge.

This code will simply let you connect to the Bluetooth printer, type a text that you want to be printed and click the "send" button to print.


android bluetooth tutorial code download

MainActivity.java - contains button listeners and functions for bluetooth connection, sending data, etc.

packagecom.example.bluetoothprinter;

importandroid.app.Activity;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.bluetooth.BluetoothSocket;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.View;
importandroid.widget.TextView;
importandroid.widget.EditText;
importandroid.widget.Button;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.Set;
importjava.util.UUID;

publicclassMainActivityextendsActivity {

// will show the statuses
TextView myLabel;

// will enable user to enter any text to be printed
EditText myTextbox;

// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;

OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;

byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

@Override
publicvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

try {

// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);

myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);

// open bluetooth connection
openButton.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(Viewv) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});

// send data typed by the user to be printed
sendButton.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(Viewv) {
try {
sendData();
} catch (IOException ex) {
}
}
});

// close bluetooth connection
closeButton.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(Viewv) {
try {
closeBT();
} catch (IOException ex) {
}
}
});

} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* This will find a bluetooth printer device
*/

voidfindBT() {

try {
mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter ==null) {
myLabel.setText("No bluetooth adapter available");
}

if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth =newIntent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() >0) {
for (BluetoothDevice device : pairedDevices) {

// MP300 is the name of the bluetooth printer device
if (device.getName().equals("MP300")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* Tries to open a connection to the bluetooth printer device
*/

voidopenBT() throwsIOException {
try {
// Standard SerialPortService ID
UUID uuid =UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();

beginListenForData();

myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* After opening a connection to bluetooth printer device,
* we have to listen and check if a data were sent to be printed.
*/

voidbeginListenForData() {
try {
finalHandler handler =newHandler();

// This is the ASCII code for a newline character
finalbyte delimiter =10;

stopWorker =false;
readBufferPosition =0;
readBuffer =newbyte[1024];

workerThread =newThread(newRunnable() {
publicvoidrun() {
while (!Thread.currentThread().isInterrupted()
&&!stopWorker) {

try {

int bytesAvailable = mmInputStream.available();
if (bytesAvailable >0) {
byte[] packetBytes =newbyte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i =0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes =newbyte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
finalString data =newString(
encodedBytes, "US-ASCII");
readBufferPosition =0;

handler.post(newRunnable() {
publicvoidrun() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}

} catch (IOException ex) {
stopWorker =true;
}

}
}
});

workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* This will send data to be printed by the bluetooth printer
*/

voidsendData() throwsIOException {
try {

// the text typed by the user
String msg = myTextbox.getText().toString();
msg +="\n";

mmOutputStream.write(msg.getBytes());

// tell the user data were sent
myLabel.setText("Data Sent");

} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* Close the connection to bluetooth printer.
*/

voidcloseBT() throwsIOException {
try {
stopWorker =true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}


activity_main.xml - our user interface, contains a TextView, EditText and three Buttons.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />

<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"
android:background="@android:drawable/editbox_background" />

<Button
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/entry"
android:layout_marginLeft="10dip"
android:text="Open" />

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/open"
android:layout_toLeftOf="@id/open"
android:text="Send" />

<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/send"
android:layout_toLeftOf="@id/send"
android:text="Close" />

</RelativeLayout>

AndroidManifest.xml - we are going to have a BLUETOOTH permission.

<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothprinter"
android:versionCode="1"
android:versionName="1.0">

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />

<supports-screensandroid:anyDensity="true" />

<uses-permissionandroid:name="android.permission.BLUETOOTH" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />

<categoryandroid:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Android Output:

UI on my Android phone.

Device Output:

android bluetooth printer
I shoud have typed "Google". Click to enlarge.

Thanks to a code from project green giant for helping me figure it out.

Two Example Usage of jQuery On() Method

$
0
0
How are you guys? Many friends asks me what is the use of jQuery on() method, where and when can we use it and why is it important. So in this tutorial, I'm going to give you two example situations where we can use the jQuery on() method.

Loading and submitting a from without page refresh. Click to enlarge.

By definition, jQuery on() method attaches an event handler function (click, submit, etc.) to one or more elements (div, p, etc.). In my experience, I used jQuery on() when:

  • I want to load a new HTML form on a DIV and submit it without page refresh.
  • I want to reload a list of records and use the actions like 'Delete'.
By the way, you can download all the codes used in this post:

free code download - jQuery On() Tutorial

Loading Different Forms to a DIV

This code can load the 'Add User' and 'Add Role' form to the 'formContainer' DIV (one at a time). Our goal is to submit the form without page refresh. To achieve that we are going to use the on() method. See the live demo:

load and submit form with on() - jQuery On() Tutorial - live demo

form_w_on.php code:

<html>
<head>
<title>jQuery On() Tutorial - submit with on()</title>

<style>
#addNewUser, #addNewRole{
cursor:pointer;
float:left;
text-decoration:underline;
}

#formContainer{
border:thin solid #000;
padding:0.5em;
margin:1em 0 0 0;
}

.clearBoth{
clear:both;
}
</style>

</head>
<body>

<divid='addNewUser'>[+ New User]</div>
<divid='addNewRole'>[+ New Roles]</div>

<divclass='clearBoth'></div>

<divid='formContainer'>
<!--here is where the form will be loaded -->
</div>

<scriptsrc='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){

// when user clicks '[+ New User]', it will load the add_user.php file
$('#addNewUser').click(function(){

$('#formContainer').load('add_user.php', function(){
console.log('user form loaded!');
});

});

// when user clicks '[+ New Roles]', it will load the add_role.php file
$('#addNewRole').click(function(){
$('#formContainer').load('add_role.php', function(){
console.log('role form loaded!');
});
});

// when the user submits the 'add new user' form
$(document).on('submit', '#addUserForm', function(){
alert('Add new user form is submitted!');
returnfalse;
});

// when the user submits the 'add new role' form
$(document).on('submit', '#addRoleForm', function(){
alert('Add new role form is submitted!');
returnfalse;
});


});
</script>

</body>
</html>

add_user.php code:
<formid='addUserForm'>
<div>Firstname: <inputtype='text'name='firstname' /></div>
<div>Lastname: <inputtype='text'name='lastname' /></div>
<div><inputtype='submit'value='Save' /></div>
</form>

add_role.php code:
<formid='addRoleForm'>
<div>User Role: <inputtype='text'name='role' /></div>
<div>Description: <inputtype='text'name='description' /></div>
<div><inputtype='submit'value='Save' /></div>
</form>

Without the on() method, jQuery code usually looks like this (form_w_out_on.php):
<script>
$(document).ready(function(){

// when user clicks '[+ New User]', it will load the add_user.php file
$('#addNewUser').click(function(){

$('#formContainer').load('add_user.php', function(){
console.log('user form loaded!');
});

});

// when user clicks '[+ New Roles]', it will load the add_role.php file
$('#addNewRole').click(function(){
$('#formContainer').load('add_role.php', function(){
console.log('role form loaded!');
});
});

// when the user submits the 'add new user' form
$('#addUserForm').submit(function() {
alert('Add user form is submitted!');
returnfalse;
});

// when the user submits the 'add new role' form
$('#addRoleForm').submit(function() {
alert('Add new role form is submitted!');
returnfalse;
});

});
</script>
Here's a live demo without using the on() method, it reloads the whole page.

load and submit form without on() - jQuery On() Tutorial - live demo


Loading Table List to a DIV

jquery on() tutorial - Loading Table List to a DIV

In this example, when the user clicks on the "[Load List]" text, it will load a table list of data (list.php) with a 'Delete' action right across each records.

Loading Table List to a DIV - jQuery on() tutorial

index.php code:

<html>
<head>
<title>jQuery on() tutorial - loading lists</title>

<style>
#myTable{
float:left;
margin:1em 0 0 0;
}

#myTableth,
#myTabletd{
border:thin solid #000;
padding:1em;
}

.deleteAction{
cursor:pointer;
}

#loadAction{
cursor:pointer;
text-decoration:underline;
}
</style>

</head>
<body>

<divid='loadAction'>[Load List]</div>

<divid='listContainer'>
<!--here is where the form will be loaded -->
</div>

<scriptsrc='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){

$('#loadAction').click(function(){

$('#listContainer').load('list.php', function(){
console.log('list loaded!');
});

});

/*
// using this code won't pop up 'Are you sure?'
$('.deleteAction').click(function(){
if(confirm('Are you sure?'){
      // do things if ok
        }
});
*/


$(document).on('click', '.deleteAction', function(){
if(confirm('Are you sure?')){
             // do things if ok
        }
});

});
</script>


</body>
</html>

Similarly, as indicated in the code comments, 'Are you sure?' alert dialog won't be shown without the help of the jQuery on() method.

list.php - the data to be loaded in the listContainer div.

<tableid='myTable'>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>Mike Dalisay</td>
<td>
<divclass='deleteAction'>Delete</div>
</td>
</tr>
<tr>
<td>Marykris De Leon</td>
<td>
<divclass='deleteAction'>Delete</div>
</td>
</tr>
</table>

There are other previously used methods almost similar the jQuery on(), like live() and delegate(). But among those methods, jQuery on() is recommended to use (if you're using jQuery 1.7+). Users of older versions of jQuery should use delegate() in preference to live().

If you want to read more about this topic, herearesomelinks that can help.

Salt, Hash and Store Passwords Securely with Phpass

$
0
0

What is password hashing?

It turns a string (of any length) to a fixed length "fingerprint" that cannot be reversed. For example, my password is "i1love2coding3", when hashed, it can be converted to a 60 character "ytwqwxpbx1oxbfvmpoaafckmat2zkdsjaxsmxwqrawxqbmifcojt3xevrgtp" which will be stored to the database.

Why do we have to hash passwords?

I think the main reason why we have to hash passwords is to prevent passwords from being stolen or compromised.
    You see, even if someone steal your database, they will never read your actual or cleartext password.

    I know that some PHP frameworks or CMS already provide this functionality, but I believe that it is important for us to know how its implementation can be made.

    Saved password was salted and hashed.

    We are going to use a Portable PHP Password Hashing Framework called phpass (pronounced "pH pass") recommended by a lot of forums and is used by some famous Web applications like phpBB3, WordPressDrupalVanilla, etc.

    This post will focus and provide you a quick grasp and basic idea on how to salt, hash and store passwords in a MySQL database. This is essential to your PHP login script.

    php hash password download code free

    Let's Code

    Our SQL table structure looks like this:

    CREATETABLEIF NOT EXISTS `users` (
    `id`int(11) NOT NULL AUTO_INCREMENT,
    `email`varchar(32) NOT NULL,
    `password`char(60) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

    libs/PasswordHash.php - our password framework file, yes, it is just this one file. You can download it here.

    libs/DbConnect.php - configuration to be connected to database.

    register.php - The user registration page, this is where we are going to save the user's password. On this example web app, we require these two fields only during registration.

    <html>
    <head>
    <title>registration page - php salt and hash password - www.codeofaninja.com</title>
    <linktype="text/css"rel="stylesheet"href="css/style.css" />
    </head>
    <body>

    <divid="loginForm">

    <?php
    // save the username and password
    if($_POST){

    try{
    // load database connection and password hasher library
    require'libs/DbConnect.php';
    require'libs/PasswordHash.php';

    /*
    * -prepare password to be saved
    * -concatinate the salt and entered password
    */

    $salt="ipDaloveyBuohgGTZwcodeRJ1avofZ7HbZjzJbanDS8gtoninjaYj48CW";
    $password=$salt.$_POST['password'];

    /*
    * '8' - base-2 logarithm of the iteration count used for password stretching
    * 'false' - do we require the hashes to be portable to older systems (less secure)?
    */

    $hasher=newPasswordHash(8,false);
    $password=$hasher->HashPassword($password);

    // insert command
    $query="INSERT INTO users SET email = ?, password = ?";

    $stmt=$con->prepare($query);

    $stmt->bindParam(1, $_POST['email']);
    $stmt->bindParam(2, $password);

    // execute the query
    if($stmt->execute()){
    echo"<div>Successful registration.</div>";
    }else{
    echo"<div>Unable to register. <a href='register.php'>Please try again.</a></div>";
    }

    }

    //to handle error
    catch(PDOException$exception){
    echo"Error: ".$exception->getMessage();
    }
    }

    // show the registration form
    else{
    ?>

    <!--
    -where the user will enter his email and password
    -required during registration
    -we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
    -->

    <formaction="register.php"method="post">

    <divid="formHeader">Registration Form</div>

    <divid="formBody">
    <divclass="formField">
    <inputtype="email"name="email"requiredplaceholder="Email" />
    </div>

    <divclass="formField">
    <inputtype="password"name="password"requiredplaceholder="Password" />
    </div>

    <div>
    <inputtype="submit"value="Register"class="customButton" />
    </div>
    <divid='userNotes'>
    Already have an account? <ahref='login.php'>Login</a>
    </div>
    </div>

    </form>

    <?php
    }
    ?>

    </div>

    </body>
    </html>


    login.php - the user login page, we are going to check if the users's password is valid or not .

    <html>
    <head>
    <title>login page - php salt and hash password - www.codeofaninja.com</title>
    <linktype="text/css"rel="stylesheet"href="css/style.css" />
    </head>
    <body>

    <divid="loginForm">

    <?php
    // form is submitted, check if acess will be granted
    if($_POST){

    try{
    // load database connection and password hasher library
    require'libs/DbConnect.php';
    require'libs/PasswordHash.php';

    // prepare query
    $query="select email, password from users where email = ? limit 0,1";
    $stmt=$con->prepare( $query );

    // this will represent the first question mark
    $stmt->bindParam(1, $_POST['email']);

    // execute our query
    $stmt->execute();

    // count the rows returned
    $num=$stmt->rowCount();

    if($num==1){

    //store retrieved row to a 'row' variable
    $row=$stmt->fetch(PDO::FETCH_ASSOC);

    // hashed password saved in the database
    $storedPassword=$row['password'];

    // salt and entered password by the user
    $salt="ipDaloveyBuohgGTZwcodeRJ1avofZ7HbZjzJbanDS8gtoninjaYj48CW";
    $postedPassword=$_POST['password'];
    $saltedPostedPassword=$salt.$postedPassword;

    // instantiate PasswordHash to check if it is a valid password
    $hasher=newPasswordHash(8,false);
    $check=$hasher->CheckPassword($saltedPostedPassword, $storedPassword);

    /*
    * access granted, for the next steps,
    * you may use my php login script with php sessions tutorial :)
    */

    if($check){
    echo"<div>Access granted.</div>";
    }

    // $check variable is false, access denied.
    else{
    echo"<div>Access denied. <a href='login.php'>Back.</a></div>";
    }

    }

    // no rows returned, access denied
    else{
    echo"<div>Access denied. <a href='login.php'>Back.</a></div>";
    }

    }
    //to handle error
    catch(PDOException$exception){
    echo"Error: ".$exception->getMessage();
    }


    }

    // show the registration form
    else{
    ?>

    <!--
    -where the user will enter his email and password
    -required during login
    -we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
    -->

    <formaction="login.php"method="post">

    <divid="formHeader">Website Login</div>

    <divid="formBody">
    <divclass="formField">
    <inputtype="email"name="email"requiredplaceholder="Email" />
    </div>

    <divclass="formField">
    <inputtype="password"name="password"requiredplaceholder="Password" />
    </div>

    <div>
    <inputtype="submit"value="Login"class="customButton" />
    </div>
    </div>
    <divid='userNotes'>
    New here? <ahref='register.php'>Register for free</a>
    </div>
    </form>

    <?php
    }
    ?>

    </div>

    </body>
    </html>

    css/style.css - just for some styling.

    body{
    font:20px"Lucida Grande", Tahoma, Verdana, sans-serif;
    color:#404040;
    }

    input[type=text],
    input[type=password],
    input[type=email]{
    padding:10px;
    width:100%;
    }

    #userNotes{
    font-size:0.7em;
    text-align:left;
    padding:10px;
    }

    #actions{
    padding:10px;
    }

    #infoMesssage{
    padding:10px;
    background-color:#BDE5F8;
    color:black;
    font-size:0.8em;
    }


    #successMessage{
    padding:10px;
    background-color:green;
    color:white;
    }

    #failedMessage{
    padding:10px;
    background-color:red;
    color:white;
    font-size:15px;
    }

    #formBody{
    padding:5px;
    }

    #loginForm{

    text-align:center;
    border:thinsolid#000;
    width:300px;
    margin:7emauto0auto;
    }

    #formHeader{
    border-bottom:thinsolidgray;
    padding:10px;
    background:#f3f3f3;
    }

    #loginForm{

    }

    .customButton {
    padding:5px;
    width:100%;
    -moz-box-shadow:inset0px1px0px0px#bbdaf7;
    -webkit-box-shadow:inset0px1px0px0px#bbdaf7;
    box-shadow:inset0px1px0px0px#bbdaf7;
    background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
    background:-moz-linear-gradient( centertop, #79bbff5%, #378de5100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
    background-color:#79bbff;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1pxsolid#84bbf3;
    display:inline-block;
    color:#ffffff;
    font-family:arial;
    font-size:15px;
    font-weight:bold;
    text-decoration:none;
    text-shadow:1px1px0px#528ecc;
    cursor:pointer;
    }

    .customButton:hover {
    background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
    background:-moz-linear-gradient( centertop, #378de55%, #79bbff100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
    background-color:#378de5;
    }

    .customButton:active {
    position:relative;
    top:1px;
    }
    /* This imageless css button was generated by CSSButtonGenerator.com */


    Demo Screenshots

    Empty database.

    Registration form.

    Just a sample HTML5 validation.

    After successful registration.

    Our database will have the record.
    Notice the password field, it was hashed.

    Our login page.

    Just an example HTML5 validation during login.

    Login with wrong credentials.

    After login with correct username and password.

    Some references

    Please note that password hashing is often wrongly referred to as "password encryption". Hashing is a more appropriate term since encryption is something that is supposed to be easily reversible. ~ phpass

    If there's something you want to add, something wrong, or any questions, please let me know in the comments. Thanks a lot!

    How to Build a Shopping Cart in PHP and MySQL

    $
    0
    0
    If you want to build your own online shopping cart from scratch, this post can help you get it done because today, we are building a simple website with shopping cart using PHP and MySQL. I also assume you already know something about PHP sessions.

    shopping cart in php
    Our shopping cart's product page.

    Our simple system will have three pages.
    1. Home Page - the landing page, you can also show your products here, but in our example, we will just display a welcome message.
    2. Products Page - shows your list of products with the option "add to cart" - cart icon with plus (+) sign.
    3. Cart Page - shows the list of products the user added to his cart. It has the option to "remove from cart " - cart icon with dash (-) sign.
    Code used in this post is available for download and live demo:

    shopping cart in php - download code shopping cart in php - live demo

    Preparing our Database

    SQL table we used.
    CREATETABLEIF NOT EXISTS `products` (
    `id`int(11) NOT NULL AUTO_INCREMENT,
    `name`varchar(32) NOT NULL,
    `price`int(11) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

    --
    -- Dumping data for table `products`
    --

    INSERT INTO`products` (`id`, `name`, `price`) VALUES
    (1, 'LG P880 4X HD', 336),
    (2, 'Google Nexus 4', 299),
    (3, 'Samsung Galaxy S4', 600);

    libs/DbConnect.php - will help us connect to the database.

    Navigation

    Navigation.php - contains the nagivation links to the home, products and cart page. This file is included to the main sections of our system.

    <?php
    // to count items in the cart
    $cartItemCount=count($_SESSION['cart']);
    ?>
    <divclass='navigation'>
    <ahref='index.php'class='customButton'>Home</a>
    <ahref='Products.php'class='customButton'>View Products</a>
    <ahref='Cart.php'class='customButton'>View Cart <?php echo"({$cartItemCount})"; ?></a>
    </div>

    Welcoming Online Shoppers

    Index.php - your customers or online shoppers should feel welcome to your site. I don't know how you design this but the code below is just a very simple example.
    <?php
    session_start();
    ?>
    <html>
    <head>
    <title>php shopping cart tutorial - home - codeofaninja.com</title>
    <linktype="text/css"rel="stylesheet"href="css/style.css" />
    </head>
    <body>

    <divclass='sectionContainer'>
    <divclass='sectionHeader'>Home</div>
    <?php
    // this will make 'home', 'view products' and 'view cart' appear
    include'Navigation.php'
    ?>

    <divclass='sectionContents'>
    Welcome to Mike's shopping website!
    </div>
    </div>

    </body>
    </html>

    Listing Your Products

    Products.php - lists products from our database.

    <?php
    session_start();
    ?>
    <html>
    <head>
    <title>php shopping cart tutorial - products - codeofaninja.com</title>
    <linktype="text/css"rel="stylesheet"href="css/style.css" />
    </head>
    <body>


    <divclass='sectionContainer'>
    <divclass='sectionHeader'>Products</div>
    <?php
    // this will make 'home', 'view products' and 'view cart' appear
    include'Navigation.php'
    ?>

    <divclass='sectionContents'>

    <?php
    if($_GET['action']=='add'){
    echo"<div>".$_GET['name'] ." was added to your cart.</div>";
    }

    if($_GET['action']=='exists'){
    echo"<div>".$_GET['name'] ." already exists in your cart.</div>";
    }

    require"libs/DbConnect.php";

    $query="SELECT id, name, price FROM products";
    $stmt=$con->prepare( $query );
    $stmt->execute();

    $num=$stmt->rowCount();

    if($num>0){
    echo"<table border='0'>";//start table

    // our table heading
    echo"<tr>";
    echo"<th class='textAlignLeft'>Product Name</th>";
    echo"<th>Price (USD)</th>";
    echo"<th>Action</th>";
    echo"</tr>";

    while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);

    //creating new table row per record
    echo"<tr>";
    echo"<td>{$name}</td>";
    echo"<td class='textAlignRight'>{$price}</td>";
    echo"<td class='textAlignCenter'>";
    echo"<a href='addToCart.php?id={$id}&name={$name}' class='customButton'>";
    echo"<img src='images/add-to-cart.png' title='Add To Cart' />";
    echo"</a>";
    echo"</td>";
    echo"</tr>";
    }

    echo"</table>";
    }

    // no products in the database
    else{
    echo"No products found.";
    }
    ?>
    </div>
    </div>

    </body>
    </html>


    Adding Products To Cart

    AddToCart.php - adds the product ID to the 'cart' session array. It also checks if the ID is already added in the session to prevent duplicate products in the cart. This file is triggered when the user clicked the 'add to cart' icon.
    <?php
    session_start();

    // get the product id
    $id=$_GET['id'];
    $name=$_GET['name'];

    /*
    * check if the 'cart' session array was created
    * if it is NOT, create the 'cart' session array
    */

    if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] =array();
    }

    // check if the item is in the array, if it is, do not add
    if(in_array($id, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    header('Location: Products.php?action=exists&id'.$id.'&name='.$name);
    }

    // else, add the item to the array
    else{
    array_push($_SESSION['cart'], $id);

    // redirect to product list and tell the user it was added to cart
    header('Location: Products.php?action=add&id'.$id.'&name='.$name);
    }

    ?>

    Listing Products in the Cart

    Cart.php - lists products added to the users' cart.

    <?php
    session_start();
    ?>
    <html>
    <head>
    <title>php shopping cart tutorial - cart - codeofaninja.com</title>
    <linktype="text/css"rel="stylesheet"href="css/style.css" />
    </head>
    <body>

    <divclass='sectionContainer'>
    <divclass='sectionHeader'>Shopping Cart</div>
    <?php
    // this will make 'home', 'view products' and 'view cart' appear
    include'Navigation.php'
    ?>

    <divclass='sectionContents'>
    <?php
    if($_GET['action']=='removed'){
    echo"<div>".$_GET['name'] ." was removed from cart.</div>";
    }

    if(isset($_SESSION['cart'])){
    $ids="";
    foreach($_SESSION['cart'] as$id){
    $ids=$ids.$id.",";
    }

    // remove the last comma
    $ids=rtrim($ids, ',');

    require"libs/DbConnect.php";

    $query="SELECT id, name, price FROM products WHERE id IN ({$ids})";
    $stmt=$con->prepare( $query );
    $stmt->execute();

    $num=$stmt->rowCount();

    if($num>0){
    echo"<table border='0'>";//start table

    // our table heading
    echo"<tr>";
    echo"<th class='textAlignLeft'>Product Name</th>";
    echo"<th>Price (USD)</th>";
    echo"<th>Action</th>";
    echo"</tr>";

    //also compute for total price
    $totalPrice=0;

    while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);

    $totalPrice+=$price;

    //creating new table row per record
    echo"<tr>";
    echo"<td>{$name}</td>";
    echo"<td class='textAlignRight'>{$price}</td>";
    echo"<td class='textAlignCenter'>";
    echo"<a href='removeFromCart.php?id={$id}&name={$name}' class='customButton'>";
    echo"<img src='images/remove-from-cart.png' title='Remove from cart' />";
    echo"</a>";
    echo"</td>";
    echo"</tr>";
    }

    echo"<tr>";
    echo"<th class='textAlignCenter'>Total Price</th>";
    echo"<th class='textAlignRight'>{$totalPrice}</th>";
    echo"<th></th>";
    echo"</tr>";

    echo"</table>";
    echo"<br /><div><a href='#' class='customButton'>Checkout</a></div>";
    }else{
    echo"<div>No products found in your cart. :(</div>";
    }

    }else{
    echo"<div>No products in cart yet.</div>";
    }
    ?>
    </div>
    </div>

    </body>
    </html>

    Removing Products From Cart

    RemoveFromCart.php - removes product ID the 'cart' session array. This file is triggered when the user clicked the 'remove from cart' icon.
    <?php
    session_start();

    // get the product id
    $id=$_GET['id'];
    $name=$_GET['name'];

    /*
    * check if the 'cart' session array was created
    * if it is NOT, create the 'cart' session array
    */

    if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] =array();
    }

    // remove the item from the array
    $_SESSION['cart'] =array_diff($_SESSION['cart'], array($id));

    // redirect to product list and tell the user it was added to cart
    header('Location: Cart.php?action=removed&id='.$id.'&name='.$name);
    ?>

    Styling Our Online Shop

    css/style.css - to make our simple system user friendly.
    body{
    font:1em"Lucida Grande", Tahoma, Verdana, sans-serif;
    color:#404040;
    }

    .navigation{

    padding:1em;
    }

    .sectionContents{

    padding:01em1em1em;
    }

    .sectionContentstable{
    width:100%;
    }

    .sectionContentstableth{
    padding:0.5em;
    background-color:#f3f3f3;
    }

    .sectionContentstabletd{
    padding:0.5em;
    background-color:#f3f3f3;
    }

    .sectionContainer{

    text-align:center;
    border:thinsolid#000;
    width:30em;
    margin:7emauto0auto;
    }

    .sectionHeader{
    font-size:1.5em;
    border-bottom:thinsolidgray;
    padding:10px;
    background:#f3f3f3;
    }

    .textAlignCenter{
    text-align:center;
    }

    .textAlignLeft{
    text-align:left;
    }

    .textAlignRight{
    text-align:right;
    }

    .customButton {
    padding:5px;
    -moz-box-shadow:inset0px1px0px0px#bbdaf7;
    -webkit-box-shadow:inset0px1px0px0px#bbdaf7;
    box-shadow:inset0px1px0px0px#bbdaf7;
    background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
    background:-moz-linear-gradient( centertop, #79bbff5%, #378de5100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
    background-color:#79bbff;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1pxsolid#84bbf3;
    display:inline-block;
    color:#ffffff;
    font-family:arial;
    font-size:15px;
    font-weight:bold;
    text-decoration:none;
    text-shadow:1px1px0px#528ecc;
    cursor:pointer;
    }

    .customButton:hover {
    background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
    background:-moz-linear-gradient( centertop, #378de55%, #79bbff100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
    background-color:#378de5;
    }

    .customButton:active {
    position:relative;
    top:1px;
    }

    Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code. :)

    Copy or Move File From One Directory to Another on Android

    $
    0
    0
    Today we are going to take a look at how to programmatically "copy" or "move" a file from one directory to another on Android. In case you want to be clarified about the difference, copying a file means the file will be seen on another directory (target location) without deleting the original file from the source location. Moving a file means the file will be seen in another directory and the

    .htaccess Rewrite Rule Examples to Achieve Clean URLs

    $
    0
    0
    Our code for today will make your website URLs clean and attractive. Clean URLs are user and SEO friendly, it does not contain any query string (e.g. param1=something&id=1111) thus giving your users and search engines (like Google) an idea what your link is all about once it was shared or indexed. Smashing Magazine has this beautiful clean URL. We are going to use .htaccess (hypertext

    Show ListView as Drop-down, an Android Spinner Alternative

    $
    0
    0
    Our code for today will give us an alternative to using the Android spinner. This ListView drop-down functions like a spinner but: I love how it looks and response to user touch, it feels smoother and faster than a spinner. It can also be easily customized, you won't have to get stuck with default spinner look.  It can be triggered on any view elements such as a Button, Layout, TextView or

    Android HTTP Example to Post File and Text Data

    $
    0
    0
    Hi guys! Today we are going to code an example app that can post a file and text data to a web server with PHP file as a receiver. Having the ability to (do HTTP Requests) post data from android app to remote server is required for most apps. Here are some example use of this functionality: You want to get statistics on how your app is being used (you have to tell your user and they must agree

    Who are the Developers of Android?

    $
    0
    0
    Android powered devices like mobile phones, tablet computers and home appliances are everywhere nowadays. It is a delight for us to experience a high technology which is less expensive, more powerful and efficient. You know what Android is, you might be grateful, and now you are asking... "Who are the developers of Android?" Android growth in device activations. Image from Android

    How to Install Android Development Environment

    $
    0
    0
    A lot has been changed since I wrote this post: Getting Started with Google Android Development. I'm not going to remove that page but I rather keep it as an archive about how Android development environment installation was done before. Installing the Android development environment was a lot easier nowadays, thanks Google! I'm not sure when it started, but there are only two things you have

    CRUD with jQuery and PHP for a Better User Experience

    $
    0
    0
    We already have a PHP CRUD tutorial in this blog and now we are going to add some AJAX functions to it with the help of jQuery. This will enable smoother user experience and faster loading of page data because your whole page won't have to refresh every time. For our code's final output, here's a video demo: Let's Code! Please note that this is not a production-ready code. This tutorial

    ADB Command Basics and Setup Tutorial

    $
    0
    0
    Contents: 1.0 What is ADB? 2.0 Where can I get ADB? 3.0 How to run the ADB?      3.1 Open Command Prompt       3.2 Find adb.exe 4.0 ADB Commands      4.1 adb      4.2 adb devices           4.2.1 adb kill-server           4.2.2 adb start-server      4.3 adb shell           4.3.1 ls           4.3.2 exit           4.3.3 cd           4.3.4 rm           4.3.5 cp      4.4 adb push      4.5 adb

    Android AlertDialog with ListView

    $
    0
    0
    Android AlertDialog with ListView is part of our awesome list post here. I usually do this when I have to give users more than three choices of action. /* * Show AlertDialog with a simple list view. * * No XML needed. */ public void alertSimpleListView() { /* * WebView is created programatically here. * * @Here are the list of items to be shown in the list */

    Android AlertDialog with ScrollView

    $
    0
    0
    Android AlertDialog with ScrollView is part of our fantastic post here. If you want to show long text to the user like your terms of use or privacy policy, you can use a ScrollView with a TextView inside. /* * Show AlertDialog with ScrollView. * * We use a TextView as ScrollView's child/host */ public void alertScrollView() { /* * Inflate the XML view. * * @

    Android AlertDialog with EditText and Other Form Elements

    $
    0
    0
    Android AlertDialog with EditText and other form elements is part of our fancy post here. Here you can also save a lot of space and make your app more simple to use by reducing the number of navigation to forms. /* * Show AlertDialog with some form elements. */ public void alertFormElements() { /* * Inflate the XML view. activity_main is in * res/layout/form_elements.xml

    Android AlertDialog with WebView

    $
    0
    0
    Android AlertDialog with WebView is part of our very useful list of AlertDialog examples here. Some app that I see put their privacy policy, terms of use and other information to an online page. You can make that AlertDialog with a WebView too. /* * Show AlertDialog with web view. * * Don't forget the Internet permission on your AndroidManifest.xml */ public void alertWebView() { //

    PhpMyAdmin Export Columns

    $
    0
    0
    Sometimes you would want to export your MySQL data, but on a specific number of columns only. For example, you have a users table that has has more than two columns (firstname, lastname, username, password, etc.) and you only want to export the user's names and usernames. In short you are exporting only two columns from your users table, and PhpMyAdmin can help us with that. Here's how to do
    Viewing all 100 articles
    Browse latest View live