Dynamic checkbox with PHP and MySQL On & Off

Monday 15 July 2019

Sample HTML/PHP Form:

<?php
include('config.php');
?>

<!DOCTYPE html>
<html>
<body>

<form method="post" action="" enctype="multipart/form-data">
<?php
$sql=mysqli_query($conn,"SELECT * FROM cruds");
   
echo "<table border='1'><tr>";
$i = 0;
while( $rs=mysqli_fetch_array($sql) ) {
    echo "<td><input type='checkbox' name='bike_id[]' class='names' value='".$rs['id']."'> </td>";
    $i++;
    if($i%4==0){
        echo "</tr><tr>";
    }
}
echo "</tr></table>";     
?>
    <br>
  <input type="submit"  name="Submit">
</form>
</body>
</html>

PHP Code:

<?php
if(isset($_POST['bike_id'])){
       $invite = implode("','",$_POST['bike_id']);
        $final_id="'".$invite."'";
    echo "update cruds set status='1' where id in($final_id)";
      mysqli_query($conn,"update cruds set status='1' where id in($final_id)"); // to update 1 for checked checkbox
      mysqli_query($conn,"update cruds set status='0' where id not in($final_id)"); // to update 0 for unchecked checkbox
    }
?>

Show dropdown based on the another dropdown using PHP AJAX

Thursday 13 June 2019

Table 1: state

CREATE TABLE `state` (
  `stid` int(2) NOT NULL,
  `stname` varchar(70) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `state` (`stid`, `stname`) VALUES
(1, 'Andhra Pradesh'),
(2, 'Arunachal Pradesh'),
(3, 'Assam'),
(4, 'Bihar'),
(24, 'Tamil Nadu'),
(36, 'Puducherry');

ALTER TABLE `state`  ADD PRIMARY KEY (`stid`);

Table 2: city

CREATE TABLE `city` (
  `cyid` int(10) NOT NULL,
  `stateid` int(2) NOT NULL,
  `cyname` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `city` (`cyid`, `stateid`, `cyname`) VALUES
(1, 24, 'Cbe');

ALTER TABLE `city` ADD PRIMARY KEY (`cyid`);


HTML/PHP Form:

<form method="post" action="" enctype="multipart/form-data">
  State:
    <?php
    $sql=mysqli_query($conn,"SELECT stid,stname FROM state");
    if(mysqli_num_rows($sql)){ ?>
    <select class="form-control" name="stateid" id="stateid" required>
    <option value="">Choose State</option>
    <?php
    while($rs=mysqli_fetch_array($sql)){ ?>
    <option value="<?php echo $rs['stid']; ?>"><?php echo $rs['stname']; ?></option>
    <?php }} ?>
    </select>
  <br><br>
    City/Location:
    <select class="form-control" name="cityid" id="cityid" required>
    <option value="">Choose City/Location</option>
    </select>
</form>

JavaScript:

    <script type="text/javascript">
    $(document).ready(function() {
  $("#stateid").change(function() {
    var stateid = $(this).val();
    if(stateid != "") {
      $.ajax({
        url:"get-city.php",
        data:{c_id:stateid},
        type:'POST',
        success:function(response) {
          var resp = $.trim(response);
          $("#cityid").html(resp);
        }
      });
    }
  });
});
</script>

Combined Code:

<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>    
    <script type="text/javascript">
    $(document).ready(function() {
  $("#stateid").change(function() {
    var stateid = $(this).val();
    if(stateid != "") {
      $.ajax({
        url:"get-city.php",
        data:{c_id:stateid},
        type:'POST',
        success:function(response) {
          var resp = $.trim(response);
          $("#cityid").html(resp);
        }
      });
    }
  });
});
</script>    
</head>
<body>

<form method="post" action="" enctype="multipart/form-data">
  State: 
    <?php
    $sql=mysqli_query($conn,"SELECT stid,stname FROM state where status='1'");
    if(mysqli_num_rows($sql)){ ?>
    <select class="form-control" name="stateid" id="stateid" required>
    <option value="">Choose State</option>
    <?php
    while($rs=mysqli_fetch_array($sql)){ ?>
    <option value="<?php echo $rs['stid']; ?>"><?php echo $rs['stname']; ?></option>
    <?php }} ?>
    </select> 
  <br><br>
    City/Location:
    <select class="form-control" name="cityid" id="cityid" required>
    <option value="">Choose City/Location</option>
    </select>  
</form> 
</body>

</html>


get-city.php

<?php 
include("config.php"); 
if(isset($_POST['c_id'])) {
  $sql = "select * from city where stateid=".mysqli_real_escape_string($conn, $_POST['c_id']);
  $res = mysqli_query($conn, $sql);
  if(mysqli_num_rows($res) > 0) {
    echo "<option value=''>Choose City/Location</option>";
    while($row = mysqli_fetch_object($res)) {
      echo "<option value='".$row->cyid."'>".$row->cyname."</option>";
    }
  }
    else
    {
        echo "<option value=''>Choose City/Location</option>";
    }
} else {
  header('location: ./');
}

?>

How to update database from Textbox using PHP MySQL AJAX

Wednesday 12 June 2019

HTML/PHP Form:

<form method="post" action="" enctype="multipart/form-data">
<?php
$sql=mysqli_query($conn,"SELECT * FROM sales");
while($rs=mysqli_fetch_array($sql)){ ?>
  Invoice No:
  <input type="text" placeholder="Invoice No" class="form-control" id="price_<?php echo $rs['primary_id']; ?>"  value="<?php echo $rs['field_name']; ?>" style="width: 180px;" onchange="changevalue(this.id,this.value)">
  <br><br>
  <?php } ?>
</form>

JavaScript:

    <script type="text/javascript">
function changevalue(file_id,userval)
{
var res = file_id.split("_");
var files_id=res[1];
$.ajax
({
type: "POST",
url: "ajaxfile.php",
data: "files_id="+ files_id +"&val=1"+"&getval="+userval,
cache: false,
success: function(response)
{  alert("Updated Successfully"); }
});
}
    </script>

ajaxfile.php:

<?php
include("config.php");

$files_id=$_REQUEST['files_id'];
$user_val=$_REQUEST['getval'];
$type=$_REQUEST['val'];

if($type == '1')
{
mysqli_query($conn,"Update Query Goes Here...");
}
?>

Combined Code:

<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> 
    <script type="text/javascript">
function changevalue(file_id,userval)
{
var res = file_id.split("_");
var files_id=res[1];
$.ajax
({
type: "POST",
url: "ajaxfile.php",
data: "files_id="+ files_id +"&val=1"+"&getval="+userval,
cache: false,
success: function(response)
{  alert("Updated Successfully"); }
});
}
    </script> 
</head>
<body>

<form method="post" action="" enctype="multipart/form-data">
<?php
$sql=mysqli_query($conn,"SELECT * FROM sales");
while($rs=mysqli_fetch_array($sql)){ ?>
  Invoice No:
  <input type="text" placeholder="Invoice No" class="form-control" id="price_<?php echo $rs['primary_id']; ?>"  value="<?php echo $rs['field_name']; ?>" style="width: 180px;" onchange="changevalue(this.id,this.value)">
  <br><br>
  <?php } ?>
</form>
</body>
</html>

Explanation:

1) In form, id="price_<?php echo $rs['primary_id']; ?>". Instead of 'primary_id' here we have to mention the primary key value from the table which is unique value in table.

2) onchange="changevalue(this.id,this.value)" means it will get the current field id and the value associate with that will pass to JavaScript function.

3) In JavaScript, data: "files_id="+ files_id +"&val=1"+"&getval="+userval,
Here if you saw statically I mentioned val=1, this value will go to AJAX file. This will help us to write more AJAX function in one page only.
Eg:
<script type="text/javascript">
function changevalue(file_id,userval)
 {
          ...
          url: "ajaxfile.php",
          data: "files_id="+ files_id +"&val=1"+"&getval="+userval,
          ....
          }
function two(file_id2,userval2)
 {
          ...
          url: "ajaxfile.php",
          data: "files_id="+ files_id2 +"&val=2"+"&getval="+userval2,
          ....
          }
</script>

4) In AJAX file, we are getting all the values we posted from the php file. In AJAX I am getting the static value as $type=$_REQUEST['val']; using the $type we can write more insert/update in AJAX file.
Eg:
if($type == '1')
{
mysqli_query($conn,"Insert Query Goes Here...");
}
if($type == '2')
{
mysqli_query($conn,"Update Query Goes Here...");
}
.
.
.
.

Dynamic checkbox with PHP and MySQL

Sample HTML/PHP Form:

<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<body>

<form method="post" action="" enctype="multipart/form-data">
<?php
$sql=mysqli_query($conn,"SELECT * FROM sales");
while($rs=mysqli_fetch_array($sql)){ ?>
  Checkbox:<br>
  <input type="checkbox" name="bike_id[]" class="names" value="<?php echo ['field_name']; ?>">
  <br>
  <?php } ?>
  <input type="submit"  name="Submit">
</form>
</body>
</html>

PHP Code:

<?php
if(isset($_POST['bike_id'])){
        $invite = $_POST['bike_id'];
        print_r($invite);
    }
?>

Output:

Array ( [0] => 1 [1] => 2 )

PayUMoney Payment Gateway Integration with PHP

Tuesday 6 March 2018

We need only 3 PHP files to achieve the same.


index.php:
<?php 
define('MERCHANT_KEY', 'Your Key');
define('SALT', 'Your Salt Code');
define('PAYU_BASE_URL', 'https://sandboxsecure.payu.in');    //Testing url
//define('PAYU_BASE_URL', 'https://secure.payu.in');  //actual URL
define('SUCCESS_URL', 'Redirect URL After Success');  //add success url
define('FAIL_URL', 'Redirect URL After Failure');    //add failure url
$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
$email = "User Mail Id";
$mobile = "User Mobile No";
$firstName = "User First Name";
$lastName = "User Last Name";
$totalCost = "Enter The Amount User Needs to Pay";
$hash='';
//Below is the required format need to hash it and send it across payumoney page. UDF means User Define Fields.
//$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
$hash_string = MERCHANT_KEY."|".$txnid."|".$totalCost."|"."productinfo|".$firstName."|".$email."|||||||||||".SALT;
$hash = strtolower(hash('sha512', $hash_string));
$action = PAYU_BASE_URL . '/_payment';
?>
<form action="<?php echo $action; ?>" method="post" name="payuForm" id="payuForm" style="display: none">
    <input type="hidden" name="key" value="<?php echo MERCHANT_KEY ?>" />
    <input type="hidden" name="hash" value="<?php echo $hash ?>"/>
    <input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
    <input name="amount" type="number" value="<?php echo $totalCost; ?>" />
    <input type="text" name="firstname" id="firstname" value="<?php echo $firstName; ?>" />
    <input type="email" name="email" id="email" value="<?php echo $email; ?>" />
    <input type="text" name="phone" value="<?php echo $mobile; ?>" />
    <textarea name="productinfo"><?php echo "productinfo"; ?></textarea>
    <input type="text" name="surl" value="<?php echo SUCCESS_URL; ?>" />
    <input type="text" name="furl" value="<?php echo  FAIL_URL?>"/>
    <input type="text" name="service_provider" value="payu_paisa"/>
    <input type="text" name="lastname" id="lastname" value="<?php echo $lastName ?>" />
</form>
<script type="text/javascript">
    var payuForm = document.forms.payuForm;
    payuForm.submit();
</script>

success.php:
<?php
$status=$_POST["status"];
$firstname=$_POST["firstname"];
$amount=$_POST["amount"];
$txnid=$_POST["txnid"];
$posted_hash=$_POST["hash"];
$key=$_POST["key"];
$productinfo=$_POST["productinfo"];
$email=$_POST["email"];
$salt="Your Salt Code";

// Salt should be same Post Request

If (isset($_POST["additionalCharges"])) {
       $additionalCharges=$_POST["additionalCharges"];
        $retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
  } else {
        $retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
         }
$hash = hash("sha512", $retHashSeq);
       if ($hash != $posted_hash) {
       echo "Invalid Transaction. Please try again";
   } else {
          echo "<h3>Thank You. Your order status is ". $status .".</h3>";
          echo "<h4>Your Transaction ID for this transaction is ".$txnid.".</h4>";
          echo "<h4>We have received a payment of Rs. " . $amount . ". Your order will soon be shipped.</h4>";
   }
?>

failure.php:
<?php
$status=$_POST["status"];
$firstname=$_POST["firstname"];
$amount=$_POST["amount"];
$txnid=$_POST["txnid"];

$posted_hash=$_POST["hash"];
$key=$_POST["key"];
$productinfo=$_POST["productinfo"];
$email=$_POST["email"];
$salt="Your Salt Code";

// Salt should be same Post Request

If (isset($_POST["additionalCharges"])) {
       $additionalCharges=$_POST["additionalCharges"];
        $retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
  } else {
        $retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
         }
$hash = hash("sha512", $retHashSeq);
 
       if ($hash != $posted_hash) {
       echo "Invalid Transaction. Please try again";
   } else {
         echo "<h3>Your order status is ". $status .".</h3>";
         echo "<h4>Your transaction id for this transaction is ".$txnid.". You may try making the payment by clicking the link below.</h4>";
}
?>





To Get Location Address Using JavaScript

Wednesday 29 March 2017

<!DOCTYPE html>
<html>
  <head>
    <title>Location</title>
    <meta charset="UTF-8" />
  </head>
  <body>
     <div id="location"> </div>
   
    <script type ="text/javascript">
      function displayLocation(latitude,longitude){
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function(){
          if(request.readyState == 4 && request.status == 200){
            var data = JSON.parse(request.responseText);
            var address = data.results[0];
            var full_address=address.formatted_address;
            document.getElementById("location").innerHTML = full_address;
          }
        };
        request.send();
      };

      var successCallback = function(position){
        var x = position.coords.latitude;
        var y = position.coords.longitude;
        displayLocation(x,y);
      };

      var errorCallback = function(error){
        var errorMessage = 'Unknown error';
        switch(error.code) {
          case 1:
            errorMessage = 'Permission denied';
            break;
          case 2:
            errorMessage = 'Position unavailable';
            break;
          case 3:
            errorMessage = 'Timeout';
            break;
        }
        document.write(errorMessage);
      };

      var options = {
        enableHighAccuracy: true,
        timeout: 1000,
        maximumAge: 0
      };

      navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);
    </script>

  </body>
</html>

Simple Chessboard Program in Javascript

Thursday 19 November 2015

<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write('<table border="1">');
for(var i=0;i<=7;i++)
{
document.write('<tr>');
for(var j=0; j<=7; j++)
{
var k=i+j;
if(k%2==0)
{
document.write("<td style='width:50px;height:50px;background-color:black;'></td>");
}
else
{
document.write("<td style='width:50px;height:50px;background-color:white;'></td>");
}
}
document.write('</tr>');
}
document.write('</table>');
</script>
</body>
</html>
 

Blogger news

Blogroll

Most Reading