article

Showing posts with label web-development (PHP). Show all posts
Showing posts with label web-development (PHP). Show all posts

Wednesday, July 25, 2018

PHP Month Array List Select Box

PHP Month Array List Select Box Live-search











<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Month Array List Select Box Live-search</title>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
      <h2>PHP Month Array List Select Box Live-search</h2>
      <p>This uses <a href="https://silviomoreto.github.io/bootstrap-select/">https://silviomoreto.github.io/bootstrap-select/</a></p>
      <hr />
    </div>
<?php
$lang_Date = array(
 'Jan'   =>'January',
 'Feb'   =>'February',
 'Mar'   =>'March',
 'Apr'   =>'April',
 'May'   =>'May',
 'June'   =>'June',
 'July'   =>'July',
 'August'  =>'August',
 'Sep'  =>'September',
 'Oct'  =>'October',
 'Nov'  =>'November',
 'Dec'  =>'December',
); 
?>
    <div class="row-fluid">
      <select class="selectpicker" data-show-subtext="true" data-live-search="true">
   <?php
    foreach ($lang_Date as $key=>$value){
  $selected = ($key==$function)?" Selected=\"Selected\"": "";
  echo "<option data-subtext=\"$key\" $selected > $value </option>";
    }
    ?>
      </select>
      <span class="help-inline">Try searching for November</span>
    </div>
  </div>
</body>
</html>

Sunday, July 22, 2018

Ajax Image Upload using PHP and jQuery

Ajax Image Upload using PHP and jQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax Image Upload using PHP and jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
 e.preventDefault();
 $("#message").empty();
 $('#loading').show();
 $.ajax({
  url: "ajax_php_file.php", // Url to which the request is send
  type: "POST",             // Type of request to be send, called as method
  data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
  contentType: false,       // The content type used when sending data to the server.
  cache: false,             // To unable request pages to be cached
  processData:false,        // To send DOMDocument or non processed data file it is set to false
  success: function(data)   // A function to be called if request succeeds
  {
   $('#loading').hide();
   $("#message").html(data);
  }
 });
}));

// Function to preview image after validation
$(function() {
 $("#file").change(function() {
  $("#message").empty(); // To remove the previous error message
  var file = this.files[0];
  var imagefile = file.type;
  var match= ["image/jpeg","image/png","image/jpg"];
  if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
  {
   $('#previewing').attr('src','img/noimage.png');
   $("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
   return false;
  }
  else
  {
   var reader = new FileReader();
   reader.onload = imageIsLoaded;
   reader.readAsDataURL(this.files[0]);
  }
 });
});
function imageIsLoaded(e) {
 $("#file").css("color","green");
 $('#image_preview').css("display", "block");
 $('#previewing').attr('src', e.target.result);
 $('#previewing').attr('width', '250px');
 $('#previewing').attr('height', '230px');
};
});
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="img/noimage.png"/></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
<h4 id='loading'><img id="previewing" src="img/loader.gif"/> Loading..</h4>
<div id="message"></div>
<style>
body {
font-family: 'Roboto Condensed', sans-serif;
}
h1
{
text-align: center;
background-color: #FEFFED;
height: 70px;
color: rgb(95, 89, 89);
margin: 0 0 -29px 0;
padding-top: 14px;
border-radius: 10px 10px 0 0;
font-size: 35px;
}
.main {
position: absolute;
top: 50px;
left: 20%;
width: 450px;
height:530px;
border: 2px solid gray;
border-radius: 10px;
}
.main label{
color: rgba(0, 0, 0, 0.71);
margin-left: 60px;
}
#image_preview{
width:100%;
height:auto;
text-align: center;
color: #C0C0C0;
overflow: auto;
}
#selectImage{
padding: 19px 21px 14px 15px;
position: absolute;
bottom: 0px;
width: 414px;
background-color: #FEFFED;
border-radius: 10px;
}
.submit{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
#file {
color: red;
padding: 5px;
border: 5px solid #8BF1B0;
background-color: #8BF1B0;
margin-top: 10px;
border-radius: 5px;
box-shadow: 0 0 15px #626F7E;
margin-left: 15%;
width: 72%;
}
#message{
position:absolute;
top:120px;
left:815px;
}
#success
{
color:green;
}
#invalid
{
color:red;
}
#line
{
margin-top: 274px;
}
#error
{
color:red;
}
#error_message
{
color:blue;
}
#loading
{
display:none;
position:absolute;
top:50px;
left:850px;
font-size:25px;
}
</style>
</body>
</html>
<?php
if(isset($_FILES["file"]["type"]))
{
 $validextensions = array("jpeg", "jpg", "png");
 $temporary = explode(".", $_FILES["file"]["name"]);
 $file_extension = end($temporary);
 if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
 ) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
 && in_array($file_extension, $validextensions)) {
  if ($_FILES["file"]["error"] > 0){
   echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
  }else{
   if (file_exists("upload/" . $_FILES["file"]["name"])) {
    echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
   }else{
    $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
    $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
    move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
    echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
    echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
    echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
    echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
   }
  }
 }else{
  echo "<span id='invalid'>***Invalid file Size or Type***<span>";
 }
}
?>

Thursday, July 19, 2018

Using Stripe with PHP

Using Stripe with PHP

1. Setup the PHP SDK

We are going to use the Stripe PHP download on Github from Stripe.

2. HTML code index.html



<html>
<head>
<title>stripe php</title>
<style>
.StripeElement {
    background-color: white;
    padding: 8px 12px;
    border-radius: 4px;
    border: 1px solid transparent;
    box-shadow: 0 1px 3px 0 #e6ebf1;
    -webkit-transition: box-shadow 150ms ease;
    transition: box-shadow 150ms ease;
}
.StripeElement--focus {
    box-shadow: 0 1px 3px 0 #cfd7df;
}
.StripeElement--invalid {
    border-color: #fa755a;
}
.StripeElement--webkit-autofill {
    background-color: #fefde5 !important;
}
</style>
</head>
<body>
<form action="charge.php" method="post" id="payment-form">
  <div class="form-row">
    <label for="card-element">Credit or debit card</label>
    <div id="card-element">
      <!-- a Stripe Element will be inserted here. -->
    </div>
    <!-- Used to display form errors -->
    <div id="card-errors"></div>
  </div>
  <button>Submit Payment</button>
</form>
<!-- The needed JS files -->
<!-- JQUERY File -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Stripe JS -->
<script src="https://js.stripe.com/v3/"></script>
<!-- Your JS File -->
<script src="charge.js"></script>
</body>
</html>
3. charge.js file
// Stripe API Key
var stripe = Stripe('pk_test_Agw01Kg5ZpIuuzUwR8tGLUME'); //YOUR_STRIPE_PUBLISHABLE_KEY
var elements = stripe.elements();
// Custom Styling
var style = {
    base: {
        color: '#32325d',
        lineHeight: '24px',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
            color: '#aab7c4'
        }
    },
    invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
    }
};
// Create an instance of the card Element
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
if (event.error) {
        displayError.textContent = event.error.message;
    } else {
        displayError.textContent = '';
    }
});
// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
    event.preventDefault();
stripe.createToken(card).then(function(result) {
        if (result.error) {
            // Inform the user if there was an error
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
        } else {
            stripeTokenHandler(result.token);
        }
    });
});
// Send Stripe Token to Server
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
// Add Stripe Token to hidden input
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);
// Submit form
    form.submit();
}
4. charge.php file
<?php
require_once('/stripe-php-6.10.3/init.php');
\Stripe\Stripe::setApiKey('sk_test_mnT9JSEucLntq5fFi5hdNlce'); //YOUR_STRIPE_SECRET_KEY
// Get the token from the JS script
$token = $_POST['stripeToken'];
// This is a $20.00 charge in US Dollar.
//Charging a Customer
// Create a Customer
$name_first = "Batosai";
$name_last = "Ednalan";
$address = "New Cabalan Olongapo City";
$state = "Zambales";
$zip = "22005";
$country = "Philippines";
$phone = "09306408219";
$user_info = array("First Name" => $name_first, "Last Name" => $name_last, "Address" => $address, "State" => $state, "Zip Code" => $zip, "Country" => $country, "Phone" => $phone);
$customer = \Stripe\Customer::create(array(
    "email" => "rednalan23@gmail.com",
    "source" => $token,
 'metadata' => $user_info,
));
// Save the customer id in your own database!
// Charge the Customer instead of the card
$charge = \Stripe\Charge::create(array(
    "amount" => 2000,
 "description" => "Purchase off Caite watch",
    "currency" => "usd",
    "customer" => $customer->id,
 'metadata' => $user_info
));
print_r($charge);
// You can charge the customer later by using the customer id.

//Making a Subscription Charge
// Get the token from the JS script
//$token = $_POST['stripeToken'];
// Create a Customer
//$customer = \Stripe\Customer::create(array(
//    "email" => "paying.user@example.com",
//    "source" => $token,
//));
// or you can fetch customer id from the database too.
// Creates a subscription plan. This can also be done through the Stripe dashboard.
// You only need to create the plan once.
//$subscription = \Stripe\Plan::create(array(
//    "amount" => 2000,
//    "interval" => "month",
//    "name" => "Gold large",
//    "currency" => "cad",
//    "id" => "gold"
//));
// Subscribe the customer to the plan
//$subscription = \Stripe\Subscription::create(array(
//    "customer" => $customer->id,
//    "plan" => "gold"
//));
//print_r($subscription);
?>

Thursday, July 5, 2018

Table Edit using jquery ajax php

Table Edit using jquery ajax php





<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Edit using jquery ajax php mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:16px;
}
.head
{
background-color:#333;
color:#FFFFFF
}
.edit_tr:hover
{
background:url(img/edit.png) right no-repeat #80C8E5;
cursor:pointer;
}
.editbox
{
display:none
}
.editbox
{
font-size:16px;
width:270px;
background-color:#ffffcc;
border:solid 1px #000;
padding:4px;
}
td
{
padding:10px;
}
th
{
font-weight:bold;
text-align:left;
padding:4px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
 $(".edit_tr").click(function() {
   var ID=$(this).attr('id');
   $("#first_"+ID).hide();
   $("#first_input_"+ID).show();
  }).change(function(){
   var ID=$(this).attr('id');
   var first=$("#first_input_"+ID).val();
   var dataString = 'id='+ ID +'&name='+first;
   $("#first_"+ID).html('<img src="img/loader.gif" />');
   if(first.length>0){
     $.ajax({
   type: "POST",
   url: "ajax.php",
   data: dataString,
   cache: false,
   success: function(html)
   {
    $("#first_"+ID).html(first);
   }
     });
   }else{
     alert('Enter something.');
   }
  });
  
  $(".editbox").mouseup(function() {
   return false
  });
   $(document).mouseup(function() {
   $(".editbox").hide();
   $(".text").show();
  });
});
</script>
</head>
<body>
<div style="margin:0 auto; width:350px; padding:10px; background-color:#fff;">
<table width="100%" border="0">
 <tr class="head">
 <th>PHP Frameworks</th>
 </tr>
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
 $i=1;
 $sql = $conn->query("SELECT * from topphpframework");
 while($row = $sql->fetch_assoc()) {
  $id=$row['id'];
  $name=$row['name'];
  if($i%2) {
?>
  <tr id="<?php echo $id; ?>" class="edit_tr">
  <?php } else { ?>
  <tr id="<?php echo $id; ?>" bgcolor="#f2f2f2" class="edit_tr">
  <?php } ?>
   <td width="50%" class="edit_td">
   <span id="first_<?php echo $id; ?>" class="text"><?php echo $name; ?></span>
   <input type="text" name="name" value="<?php echo $name; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
   </td>
  </tr>
 <?php 
  $i++;
 } ?>
</table>
</div>
</body>
</html>
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
if($_POST['id'])
{
 $id=mysql_escape_String($_POST['id']);
 $name=mysql_escape_String($_POST['name']);
 $sql = "UPDATE topphpframework SET name = '$name' WHERE id = '$id' ";
 if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
 } else {
  echo "Error updating record: " . $conn->error;
 }
}
?>

Friday, June 8, 2018

Simple PHP MySQLi Login Form

Simple PHP MySQLi Login Form
//login.php
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
<title>Simple PHP MySQLi Login Form</title>
</head>
<body>
 <form method='post' action='validate_login.php' >
  <table border='1' >
   <tr>
    <td><label for='username'>User Name</label></td>
    <td><input type='text' name='username' id='username'></td>
   </tr>
   <tr>
    <td><label for='users_pass'>Password</label></td>
    <td><input name='users_pass' type='password' id='users_pass'></input></td>
   </tr>
   <tr>
    <td><input type='submit' value='Submit'/>
    <td><input type='reset' value='Reset'/>
   </tr>
  </table>
 </form>
</body>
</html>
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
$username = $_POST['username'];
$pass = $_POST['users_pass'];
$sqlc="SELECT * FROM users WHERE username = '$username' OR password = '$pass'";
if ($rsdc=mysqli_query($conn,$sqlc)){
  $total=mysqli_num_rows($rsdc); 
  if ($total == '1') {
   echo'<h1>You are a validated user.</h1>';
  }else{
 echo'<h1>Sorry, your credentials are not valid, Please try again.</h1>'; 
  } 
}
?>

Sunday, May 27, 2018

Ajax Jquery and php Page Loading

Ajax Jquery and php Page Loading

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax Jquery and php Page Loading</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
  $('.super').click(function(){
    $('#container').fadeOut();
    var a = $(this).attr('id');
    $.post("ajax_page.php?id="+a, {
    }, function(response){
  setTimeout("finishAjax('container', '"+escape(response)+"')", 400);
    });
  });
 }); 
  function finishAjax(id, response){
   $('#'+id).html(unescape(response));
   $('#'+id).fadeIn();
 } 
</script>
</head>
<body>
<div style="float:left">
<ul class="menus">
    <li><input type="button" name="test" class="super red button" id="1" value="Home" /></li>
    <li><input type="button" name="test" class="super buy button" id="2" value="About" /></li>
    <li><input type="button" name="test" class="super green button" id="3" value="Services" /></li>
</ul>
</div>
<div id="container">
<?php
 include('dbcon.php');
 $query = $conn->query("SELECT * FROM descriptions where page_type = 1 order by id desc");
 while ($row = $query ->fetch_object()) {
 $heading=$row->heading; 
 $text=$row->text;
?>
   <label><?php echo $heading;?></label>
   <br />
   <p><?php echo $text;?></p>
    <?php } ?>
</div>
<style>
ul.menus{
 list-style:none;
 margin:10px 0 0 0;
}
ul.menus li input {
 display:block;
 padding:8px 8px 8px 8px;
 text-decoration:none;
 color:#ddd;
 font-size:22px;
 text-shadow:1px 1px 1px #000;
 margin:5px 10px;
 background-color:#1f1f1f;
 border:1px solid #222;
 -moz-box-shadow:0px 0px 10px #000;
 -webkit-box-shadow:0px 0px 10px #000;
 box-shadow:0px 0px 10px #000;
 background-repeat:no-repeat;
 background-position:5px 50%;
 opacity:0.9;
 outline:none;
 width:120px;
}
ul.menus li input:hover{
 color:#fff;
 border:1px solid #303030;
 background-color:#212121;
 opacity:1.0;
 text-shadow:0px 0px 1px #fff;
}
#container{
 -moz-border-radius: 6px; 
 -webkit-border-radius: 6px;
 -moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
 -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
 padding:10px 20px 20px 20px;
 text-align:justify;
 font-size:14px;
 font-family:Arial, Helvetica, sans-serif;
 text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
 height:300px; float:left; 
 width:400px;
}
#container label{
 font-size:24px;
 color:#336699;
 font-weight:bolder;
}
</style>
</body>
</html>
//ajax_page.php
<?php
include("dbcon.php");
$getid = $_REQUEST['id'];
$sql = 'SELECT * FROM descriptions where page_type = "'.$getid.'" order by id desc';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
  $heading = $row["heading"];
  $text = $row["text"];
   echo "<label>$heading</label><br />";
   echo "<p>$text</label></p>";
    }
} else {
    echo "0 results";
}
mysqli_close($conn);
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

AJAX Pagination using jQuery, PHP and Msqli

AJAX Pagination using jQuery, PHP and Msqli
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Pagination using jQuery, PHP and Msqli</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 function showLoader(){
  $('.search-background').fadeIn(200);
 }
 function hideLoader(){
  $('.search-background').fadeOut(200);
 };
  $("#paging_button li").click(function(){
	  showLoader();
	  $("#paging_button li").css({'background-color' : ''});
	  $(this).css({'background-color' : '#006699'});
	  $("#content").load("ajaxpagenation.php?page=" + this.id, hideLoader);
	  return false;
  });
  $("#1").css({'background-color' : '#006699'});
  showLoader();
  $("#content").load("ajaxpagenation.php?page=1", hideLoader);
});
</script>
<style type="text/css">
.trash { color:rgb(209, 91, 71); }
.flag { color:rgb(248, 148, 6); }
.panel-body { padding:0px; }
.panel-footer .pagination { margin: 0; }
.panel .glyphicon,.list-group-item .glyphicon { margin-right:5px; }
.list-group { margin-bottom:0px; }
</style>
</head>
<body>
<?php
include("dbcon.php");
$per_page = 10;
$sql="SELECT * FROM country ";
if ($result=mysqli_query($conn,$sql)){
  $count=mysqli_num_rows($result);
  $pages = ceil($count/$per_page);
  mysqli_free_result($result);
}
?>
<div class="container">
    <div class="row">
        <div class="col-md-12" style="padding:30px;">
            <div class="panel panel-primary">
                <div class="panel-heading">  <div class="search-background"><img src="img/loader.gif" alt="" />Loading..</div>
                    <span class="glyphicon glyphicon-list"></span>AJAX Pagination using jQuery, PHP and Mysqli
                </div>
                <div class="panel-body">
                    <ul class="list-group">
						  <div id="content"></div>	
					</ul>
                </div>
				
				<div class="panel-footer">
                    <div class="row">
                        <div class="col-md-12">
							 <div id="paging_button" >
                            <ul class="pagination pagination-sm pull-right">
								  <?php
								  //Show page links
								  for($i=1; $i<=$pages; $i++)
								  {
								  ?>
                                <li id="<?php echo $i; ?>"><a href="#"><?php echo $i; ?></a></li>
                                <?php }?>
                            </ul>
                        </div>
						</div>
					</div>
				</div>
			</div>	
        </div>
    </div>
</div>
</body>
</html>
//ajaxpagenation.php
<?php
include("dbcon.php");
$per_page = 10;
$sqlc="SELECT * FROM country";
if ($rsdc=mysqli_query($conn,$sqlc)){
  $cols=mysqli_num_rows($rsdc); 
}
$page = $_REQUEST['page'];
$start = ($page-1)*10;

$sql = $conn->query("SELECT * FROM country ORDER BY id limit $start,10");
while($rows = $sql->fetch_assoc()) {
?>
	<li class="list-group-item">
         <img src="img/philflag.png" width="35" height="30"> <span><b><?php echo $rows['country'];?></b></span>
        <div class="pull-right action-buttons">
             <a href="#"><span class="glyphicon glyphicon-pencil"></span></a>
             <a href="#" class="trash"><span class="glyphicon glyphicon-trash"></span></a>
             <a href="#" class="flag"><span class="glyphicon glyphicon-flag"></span></a>
         </div>
  </li>
<?php } ?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Sunday, April 29, 2018

How to Load or Read XML file using PHP

How to Load or Read XML file using PHP
 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Load or Read XML file using PHP</title>
</head>
<body>
<?php
//Read Specific XML Elements
  $xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
  echo $xmldata->employee[0]->firstname . "<br/>";
  echo $xmldata->employee[1]->firstname . "<br/>";
  echo $xmldata->employee[2]->firstname; 
?><br/><br/>
<?php
//Read XML Elements In A Loop
$xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
foreach($xmldata->children() as $empl) {         
 echo $empl->firstname . ", ";     
 echo $empl->lastname . ", ";     
 echo $empl->designation . ", ";        
 echo $empl->salary . "<br/>"; 
} 
?>
<br/><br/>
<?php
$xml = simplexml_load_file('xml/employee.xml');
echo '<h2>Employees Listing</h2>';
$list = $xml->employee;
for ($i = 0; $i < count($list); $i++) {
    echo 'Name: ' . $list[$i]->firstname . '<br>';
    echo 'Salary: ' . $list[$i]->salary . '<br>';
    echo 'Position: ' . $list[$i]->designation . '<br><br>';
}
?>
</body>
</html>
//employee.xml
<?xml version="1.0"?>
<company>
 <employee>
 <firstname>Emma</firstname>
 <lastname>Cruise</lastname>
 <designation>MD</designation>
 <salary>500000</salary>
 </employee>
 <employee>
 <firstname>Olivia</firstname>
 <lastname>Horne</lastname>
 <designation>CEO</designation>
 <salary>250000</salary>
 </employee> 
 <employee>
 <firstname>Isabella</firstname>
 <lastname>Sophia</lastname>
 <designation>Finance Manager</designation>
 <salary>250000</salary>
 </employee>
</company>

Friday, April 13, 2018

PHP Function create SEO URL Friendly

PHP Function create SEO URL Friendly

strtlower make string lowercase preg_replace remove all unwanted character spaces and dashes
<?php
function seo_url($string, $seperator='-') {
   $string = strtolower($string);
   $string = preg_replace("/[^a-z0-9_\s-]/", $seperator, $string);
   $string = preg_replace("/[\s-]+/", " ", $string);
   $string = preg_replace("/[\s_]/", $seperator, $string);
   return $string;
}
$teststring = "PHP Function create SEO URL Friendly";
$seofrieldy = seo_url($teststring);
echo "www.tutorial.com/$seofrieldy/";
?>

Saturday, March 24, 2018

Multiple Image Upload Php

Multiple Image Upload Php

how to upload multiple files using a single form



<?php
if (isset($_POST['Submit'])){
while(list($key,$value) = each($_FILES['images']['name']))
 {
  if(!empty($value))
  {
   $filename = $value;
    $filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
    $add = "img/$filename";
    copy($_FILES['images']['tmp_name'][$key], $add);
    chmod("$add",0777);
  }
 }
}
?>
<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>
<form method=post action="" enctype='multipart/form-data'>
<?php
$max_no_img=4;
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]'></td></tr>";
}
?>
<tr><td colspan=2 align=center><input name="Submit" type=submit value='Add Image'></td></tr>
</form>
</table>

Saturday, March 3, 2018

jQuery PHP checkbox values to PHP $_POST variables

jQuery PHP checkbox values to PHP $_POST variables




 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery PHP checkbox values to PHP $_POST variables</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function () {
    $('#submitBtn').click (function() {
        var selected = new Array();
   $("input:checkbox[name=programming]:checked").each(function() {
    selected.push($(this).val());
   });
  var selectedString = selected.join(",");
        $.post("ajaxcheckboxvalue.php", {selected: selected },
        function(data){
            $('.result').html(data);
        });  
    });
});
</script>
</head>
<body>
<div class="container">
 <div class="row">
     <div class="col-md-6 offset-md-3">
  <h1>jQuery PHP checkbox values to PHP $_POST variables</h1>
  <div class="card" style="margin:50px 0">
                <div class="card-header">Checkbox Animation</div>
    <ul class="list-group list-group-flush">
                    <li class="list-group-item">
                        Bootstrap Checkbox Default
                                <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Default"/>
                                        <span class="default"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Primary
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Primary"/>
                                        <span class="primary"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Success
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Success"/>
                                        <span class="success"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Info
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Info"/>
                                        <span class="info"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Warning
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Warning"/>
                                        <span class="warning"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Danger
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Danger"/>
                                        <span class="danger"></span>
                                    </label>
                    </li>
                </ul>
    <div class = "result" style="padding:10px;"></div>
    <button type="button" id = "submitBtn" class="btn btn-outline-success slideright" style="margin:10px;">Submit</button> 
  </div>  
  </div>
 </div>
</div>
<style>
  @keyframes check {0% {height: 0;width: 0;}
    25% {height: 0;width: 10px;}
    50% {height: 20px;width: 10px;}
  }
  .checkbox{background-color:#fff;display:inline-block;height:28px;margin:0 .25em;width:28px;border-radius:4px;border:1px solid #ccc;float:right}
  .checkbox span{display:block;height:28px;position:relative;width:28px;padding:0}
  .checkbox span:after{-moz-transform:scaleX(-1) rotate(135deg);-ms-transform:scaleX(-1) rotate(135deg);-webkit-transform:scaleX(-1) rotate(135deg);transform:scaleX(-1) rotate(135deg);-moz-transform-origin:left top;-ms-transform-origin:left top;-webkit-transform-origin:left top;transform-origin:left top;border-right:4px solid #fff;border-top:4px solid #fff;content:'';display:block;height:20px;left:3px;position:absolute;top:15px;width:10px}
  .checkbox span:hover:after{border-color:#999}
  .checkbox input{display:none}
  .checkbox input:checked + span:after{-webkit-animation:check .8s;-moz-animation:check .8s;-o-animation:check .8s;animation:check .8s;border-color:#555}
.checkbox input:checked + .default:after{border-color:#444}
.checkbox input:checked + .primary:after{border-color:#2196F3}
.checkbox input:checked + .success:after{border-color:#8bc34a}
.checkbox input:checked + .info:after{border-color:#3de0f5}
.checkbox input:checked + .warning:after{border-color:#FFC107}
.checkbox input:checked + .danger:after{border-color:#f44336}
</style>
</body>
</html>
//ajaxcheckboxvalue.php
<?php
$selected  = $_POST['selected'];
foreach ($selected as $value) {
    echo $value . " <br/>";

}
?>

Thursday, December 1, 2016

PHPMailer Upload mail Attachment

PHPMailer Upload mail Attachment

PHPMailer-master https://github.com/PHPMailer/PHPMailer

<?php
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
 if (preg_match('/\.(doc|docx|xls|xlsx|pdf|jpeg|png)$/i', $_FILES["userfile"]["name"])) //upload
 {
  $uploadfile = $_FILES['userfile']['name'];
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        // This should be somewhere in your include_path
        require 'PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->setFrom('from@example.com', 'First Last');
        $mail->addAddress('tomail@example.com', 'John Doe');
        $mail->Subject = 'PHPMailer file sender';
        $mail->msgHTML("My message body");
        $mail->addAttachment($uploadfile);
        if (!$mail->send()) {
            $msg = "Mailer Error: " . $mail->ErrorInfo;
        } else {
            $msg = "Message sent!";
        } 
  }else {
   $msg = '<font color=red> ERROR_FAILED_TO_UPLOAD_FILE </font>';
  }
 }else{
  $msg = '<font color=red> ERROR_FAILED_TO_UPLOAD_FILE </font>';
 } 
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>PHPMailer Upload mail Attachment</title>
</head>
<body>
<?php if (empty($msg)) { ?>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
        <input type="submit" value="Send File">
    </form>
<?php } else {
    echo $msg;
} ?>
</body>
</html>

Tuesday, November 29, 2016

php Randomize Background Image

php Randomize Background Image
<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames

  $i = rand(0, count($bg)-1); // generate random number size of the array
  $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
<style type="text/css">
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
</style>

Saturday, November 26, 2016

Basic Example using SMTP (no authentication) and attachments

Basic Example using SMTP (no authentication) and attachments
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->Subject    = "PHPMailer Test Subject via smtp, basic with no authentication";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

Friday, July 29, 2016

PHP - Get Users IP Address

Get Users IP Address 

<?php
class datasource {
 function getIP() {
  $ipaddress = '';
  if (isset($_SERVER['HTTP_CLIENT_IP']))
   $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
   $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  else if(isset($_SERVER['HTTP_X_FORWARDED']))
   $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
   $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  else if(isset($_SERVER['HTTP_FORWARDED']))
   $ipaddress = $_SERVER['HTTP_FORWARDED'];
  else if(isset($_SERVER['REMOTE_ADDR']))
   $ipaddress = $_SERVER['REMOTE_ADDR'];
  else
   $ipaddress = 'UNKNOWN';
  return $ipaddress;
 }
}

$clasgetip = new datasource;
$ipaddress = $clasgetip->getIP();
echo $ipaddress;
?>

Thursday, July 7, 2016

PHP MySqli Basic usage (select, insert & update)

PHP MySqli Basic usage (select, insert & update) 

<?php
//Connect to Database
$mysqli =  mysqli_connect('host','username','password','database_name');
//object oriented style (recommended)
$mysqli = new mysqli('host','username','password','database_name');

$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

//-----------------------------------------------------------------
//SELECT Multiple Records as Associative array
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT id, product_code, product_desc, price FROM products");
print '<table border="1">';
while($row = $results->fetch_assoc()) {
    print '<tr>';
    print '<td>'.$row["id"].'</td>';
    print '<td>'.$row["product_code"].'</td>';
    print '<td>'.$row["product_name"].'</td>';
    print '<td>'.$row["product_desc"].'</td>';
    print '<td>'.$row["price"].'</td>';
    print '</tr>';
}  
print '</table>';
// Frees the memory associated with a result
$results->free();
// close connection 
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Multiple Records as Array
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT id, product_code, product_desc, price FROM products");
print '<table border="1"';
while($row = $results->fetch_array()) {
    print '<tr>';
    print '<td>'.$row["id"].'</td>';
    print '<td>'.$row["product_code"].'</td>';
    print '<td>'.$row["product_name"].'</td>';
    print '<td>'.$row["product_desc"].'</td>';
    print '<td>'.$row["price"].'</td>';
    print '</tr>';
}   
print '</table>';
// Frees the memory associated with a result
$results->free();
// close connection 
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Multiple Records as Objects
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT id, product_code, product_desc, price FROM products");
print '<table border="1">';
while($row = $results->fetch_object()) {
    print '<tr>';
    print '<td>'.$row->id.'</td>';
    print '<td>'.$row->product_code.'</td>';
    print '<td>'.$row->product_name.'</td>';
    print '<td>'.$row->product_desc.'</td>';
    print '<td>'.$row->price.'</td>';
    print '</tr>';
}  
print '</table>';
// close connection 
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Single value
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//chained PHP functions
$product_name = $mysqli->query("SELECT product_name FROM products WHERE id = 1")->fetch_object()->product_name; 
print $product_name; //output value
$mysqli->close();

//-----------------------------------------------------------------
//SELECT COUNT Total records of a table
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get total number of records
$results = $mysqli->query("SELECT COUNT(*) FROM users");
$get_total_rows = $results->fetch_row(); //hold total records in variable
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Using Prepared Statements
$search_product = "PD1001"; //product id
//create a prepared statement
$query = "SELECT id, product_code, product_desc, price FROM products WHERE product_code=?";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('s', $search_product);
//execute query
$statement->execute();
//bind result variables
$statement->bind_result($id, $product_code, $product_desc, $price);
print '<table border="1">';
//fetch records
while($statement->fetch()) {
    print '<tr>';
    print '<td>'.$id.'</td>';
    print '<td>'.$product_code.'</td>';
    print '<td>'.$product_desc.'</td>';
    print '<td>'.$price.'</td>';
    print '</tr>';
}   
print '</table>';
//close connection
$statement->close();

//Same query with multiple parameters:
$search_ID = 1; 
$search_product = "PD1001"; 
$query = "SELECT id, product_code, product_desc, price FROM products WHERE ID=? AND product_code=?";
$statement = $mysqli->prepare($query);
$statement->bind_param('is', $search_ID, $search_product);
$statement->execute();
$statement->bind_result($id, $product_code, $product_desc, $price);
print '<table border="1">';
while($statement->fetch()) {
    print '<tr>';
    print '<td>'.$id.'</td>';
    print '<td>'.$product_code.'</td>';
    print '<td>'.$product_desc.'</td>';
    print '<td>'.$price.'</td>';
    print '</tr>';

}   
print '</table>';
//close connection
$statement->close();

//-----------------------------------------------------------------
//INSERT a Record
//values to be inserted in database table
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
    print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
//Prepared Statement
//Prepared statements are very effective against SQL injection
//values to be inserted in database table
$product_code = 'P1234';
$product_name = '42 inch TV';
$product_price = '600';
$query = "INSERT INTO products (product_code, product_name, price) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('sss', $product_code, $product_name, $product_price);
if($statement->execute()){
    print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();

//-----------------------------------------------------------------
//Insert Multiple Records
//product 1
$product_code1 = '"'.$mysqli->real_escape_string('P1').'"';
$product_name1 = '"'.$mysqli->real_escape_string('Google Nexus').'"';
$product_price1 = '"'.$mysqli->real_escape_string('149').'"';
//product 2
$product_code2 = '"'.$mysqli->real_escape_string('P2').'"';
$product_name2 = '"'.$mysqli->real_escape_string('Apple iPad 2').'"';
$product_price2 = '"'.$mysqli->real_escape_string('217').'"';
//product 3
$product_code3 = '"'.$mysqli->real_escape_string('P3').'"';
$product_name3 = '"'.$mysqli->real_escape_string('Samsung Galaxy Note').'"';
$product_price3 = '"'.$mysqli->real_escape_string('259').'"';
//Insert multiple rows
$insert = $mysqli->query("INSERT INTO products(product_code, product_name, price) VALUES
($product_code1, $product_name1, $product_price1),
($product_code2, $product_name2, $product_price2),
($product_code3, $product_name3, $product_price3)");
if($insert){
    //return total inserted records using mysqli_affected_rows
    print 'Success! Total ' .$mysqli->affected_rows .' rows added.<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}

//-----------------------------------------------------------------
//Update/Delete a Records
//Updating and deleting records works similar way, just change to query string to MySql Update or delete
//MySqli Update Query
$results = $mysqli->query("UPDATE products SET product_name='52 inch TV', product_code='323343' WHERE ID=24");
//MySqli Delete Query
//$results = $mysqli->query("DELETE FROM products WHERE ID=24");
if($results){
    print 'Success! record updated / deleted'; 
}else{
    print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}

//-----------------------------------------------------------------
//Update using Prepared Statement
$product_name = '52 inch TV';
$product_code = '9879798';
$find_id = 1;
$statement = $mysqli->prepare("UPDATE products SET product_name=?, product_code=? WHERE ID=?");
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('ssi', $product_name, $product_code, $find_id);
$results =  $statement->execute();
if($results){
    print 'Success! record updated'; 
}else{
    print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}

//Delete Old Records
//Delete all records that is 1 day old, or specify X days records you want to delete.
//MySqli Delete Query
$results = $mysqli->query("DELETE FROM products WHERE added_timestamp < (NOW() - INTERVAL 1 DAY)");
if($results){
    print 'Success! deleted one day old records'; 
}else{
    print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}
?>

Monday, November 9, 2015

Jquery ajax Selectbox


Jquery ajax Selectbox  


index.php

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
 jQuery(document).ready(function(){    
  jQuery("select[name='country']").change(function(){   
   var optionValue = jQuery("select[name='country']").val();  
   jQuery.ajax({
    type: "GET",
    url: "city.php",
    data: "country="+optionValue+"&status=1",
    beforeSend: function(){ jQuery("#ajaxLoader").show(); },
    complete: function(){ jQuery("#ajaxLoader").hide(); },
    success: function(response){
     jQuery("#cityAjax").html(response);
     jQuery("#cityAjax").show();
    }
   });    
  });
 });
</script>
Countries: 
<select name="country">
 <option value="">Please Select</option>
 <option value="1">Nepal</option>
 <option value="2">India</option>
 <option value="3">China</option>
 <option value="4">USA</option>
 <option value="5">UK</option>
</select>
<div id="ajaxLoader" style="display:none"><img src="../ajax-loader.gif" alt="loading..."></div>
<div id="cityAjax" style="display:none">
 <select name="city">
  <option value="">Please Select</option>
 </select>
</div>
city.php
<?php
$country = $_GET['country'];
if(!$country) {
 return false;
}
$cities = array(
   1 => array('Kathmandu','Bhaktapur','Patan','Pokhara','Lumbini'),
   2 => array('Delhi','Mumbai','Kolkata','Bangalore','Hyderabad','Pune','Chennai','Jaipur','Goa'),
   3 => array('Beijing','Chengdu','Lhasa','Macau','Shanghai'),
   4 => array('Los Angeles','New York','Dallas','Boston','Seattle','Washington','Las Vegas'),
   5 => array('Birmingham','Bradford','Cambridge','Derby','Lincoln','Liverpool','Manchester')
  );
$currentCities = $cities[$country];
?>
City: 
<select name="city">
 <option value="">Please Select</option>
 <?php
 foreach($currentCities as $city) {
  ?>
  <option value="<?php echo $city; ?>"><?php echo $city; ?></option>
  <?php 
 }
 ?>
</select>

Sunday, November 8, 2015

Add Edit Delete Using PHP Class

Add Edit Delete Using PHP Class






 
<?php
$db['host']     = 'localhost';   //Your database host, I.E. localhost
$db['username'] = 'root';        //Your database username
$db['password'] = '';            //Your database password
$db['db']       = 'mycmsdb';   //Your database name
$db['prefix']   = '';            //Your table prefix, can be left blank

class MySQLDB
{
        var $dbhost;
        var $dbuser;
        var $dbpass;
        var $dbname;
        var $dblink;
        var $qrystr;
        var $result;
        var $dbprefix;
        
        function MySQLDB($dbhost, $dbuser, $dbpass, $dbname, $dbprefix)
        {
                $this->dbhost=$dbhost;
                $this->dbuser=$dbuser;
                $this->dbpass=$dbpass;
                $this->dbname=$dbname;
                $this->dbprefix=$dbprefix;
        }
        
        function connectdb()
        {
                $this->dblink=mysql_connect($this->dbhost,$this->dbuser,$this->dbpass) or die($this->show_error());
        }
        
        function selectdb()
        {
                mysql_select_db($this->dbname) or die($this->show_error());
        }
        
        function show_error()
        {
                print mysql_error($this->dblink);
        }
        
        function query($qry="")
        {
                if(!empty($qry)) $this->qrystr=$qry;
                if(empty($this->qrystr)) die("Error: Query string is empty.");
                else $this->result=mysql_query($this->qrystr,$this->dblink) or die($this->show_error());                
        }
        
        function setqrystr($qry)
        {
                $this->qrystr=$qry;
        }
        
        function get_insert_id()
        {
                return mysql_insert_id($this->dblink);
        }
        
        function getrow()
        {
                return mysql_fetch_row($this->result);
        }
        
        function getarr()
        {
                return mysql_fetch_array($this->result,MYSQL_ASSOC);
        }
        
        function getobj()
        {
                return mysql_fetch_object($this->result);
        }
        
        function getaffectedrows()
        {
                return mysql_affected_rows($this->dblink);
        }
        
        function getrownum()
        {
                return mysql_num_rows($this->result);
        }
        
        function freeresult()
        {
                mysql_free_result($this->result);
        }
        
        function closedb()
        {
                mysql_close($this->dblink);
        }
        
        function __destruct()
        {
                mysql_close($this->dblink);
        }
        
        function tb($tablename)
        {
                if(empty($this->dbprefix))        return $tablename;
                else return $this->dbprefix."_".$tablename;
        }
}
//Hostname,Username,Password,Database,table prefix
$db=new MySQLDB($db['host'], $db['username'], $db['password'], $db['db'], $db['prefix']);
$db->connectdb();
$db->selectdb();
?>

<?
//Examples
$qry="SELECT * FROM rme_bookings WHERE city='angeles'";
$db->query($qry);
$row=$db->getrow();
$maxtime=$row[0]; 
echo $maxtime;
//Udate
$qry="UPDATE ".$db->tb("admin")." SET uname='$uname', pwd='$pwd', email='$email' WHERE uid=$auid";
$db->query($qry);
 if($db->getaffectedrows()==0) $err[0]="Nothing altered! Try again.";
 else  $err[0]="Profile updated successfully."; 

$qry="SELECT conf_value FROM ".$db->tb("configuration")." WHERE conf_name='AUTO_FILE_DELETE'";
$db->query($qry);
$row=$db->getrow();
if($row[0]=="Yes")
{
 $now=time();
 $qry="SELECT dir, file_name FROM ".$db->tb("fileinfo")." WHERE expire_time<$now";
 $db->query($qry);
 while($row=$db->getrow())
 {
  @unlink("uploads/".$row[1]."/".$row[2]);
  @rmdir("uploads/".$row[1]);
 }
 $qry="DELETE FROM ".$db->tb("fileinfo")." WHERE expire_time<$now";
 $db->query($qry);
}

 $qry="SELECT uname, pwd, email FROM ".$db->tb("admin")." WHERE uid=$auid";
$db->query($qry);
 $row=$db->getrow();
 $uname=$row[0];
$pwd=$row[1];
 $email=$row[2];
  
$qry="SELECT * FROM ".$db->tb("fileinfo")." ORDER BY upload_time DESC";
$db->query($qry);
while($row=$db->getarr())
{
 $status="Ok";
 $idkey = $row["idkey"];
 if($row["no_of_dwnld"]>=$row["max_dwnld"]) $status="Count Exceeded";
 if($row["expire_time"]<time()) $status="Expired";
 if($row["link_status"]==0) $status="Suspended";
}   

$qry="DELETE FROM ".$db->tb("adminlog")." WHERE uid=".$row[0]." and timein=".$row1[0];
$db->query($qry);  

$qry="INSERT INTO ".$db->tb("adminlog")."(uid,timein,ip) VALUES(".$row[0].",".time().",'".$_SERVER['REMOTE_ADDR']."')";
$db->query($qry);

$db->query("UPDATE ".$db->tb("admin")." SET `pwd`='".$md5."'");
$row=$db->getrow();
?>

Friday, November 6, 2015

Using phpMailer to Send Mail through PHP

Using phpMailer to Send Mail through PHP

Download the PHPMailer script  

index.html
<form method="post" action="email.php">
  Email: <input name="email" id="email" type="text" /><br />
  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
</form>
mail.php
<?php
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
require("lib/PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer@tutorial101.blogspot.com
// pass: password
$mail->Username = "send_from_PHPMailer@tutorial101.blogspot.com";  // SMTP username
$mail->Password = "123456789"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("ednalan@tutorial101.blogspot.com", "Ednalan");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website!";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body    = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}
echo "Message has been sent";
?>

Tuesday, July 21, 2015

Image Preview Thumbnails before upload using jQuery & PHP

Image Preview Thumbnails before upload using jQuery & PHP
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script>
$(document).ready(function(){
    $('#file-input').on('change', function(){ //on file input change
        if (window.File && window.FileReader && window.FileList && window.Blob) //check File API supported browser
        {
            $('#thumb-output').html(''); //clear html of output element
            var data = $(this)[0].files; //this file data
            
            $.each(data, function(index, file){ //loop though each file
                if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){ //check supported file type
                    var fRead = new FileReader(); //new filereader
                    fRead.onload = (function(file){ //trigger function on successful read
                    return function(e) {
                        var img = $('<img/>').addClass('thumb').attr('src', e.target.result); //create image element 
                        $('#thumb-output').append(img); //append image to output element
                    };
                    })(file);
                    fRead.readAsDataURL(file); //URL representing the file's data.
                }
            });
            
        }else{
            alert("Your browser doesn't support File API!"); //if File API is absent
        }
    });
});
</script>
<style>
.thumb{
    margin: 10px 5px 0 0;
    width: 100px;
}
.alert-info {
  background-color: #d9edf7;
  border-color: #bce8f1;
  color: #31708f;
}
.alert {
  padding: 5px 10px;
  margin-bottom: 10px;
  border: 1px solid transparent;
  border-radius: 4px;
}
</style>
<div class="alert alert-info">
<input type="file" id="file-input" multiple=""><p></p>
<div id="thumb-output"></div>
</div>

Related Post