Hi Everyone I am trying to implement the EasyPay Pakistan payment gateway for my website but i am getting this error Parameter Authentication failed my code is below which is in plugin they provided:
<?php
require '../../../wp-config.php';
$storeId = get_option('storeId');
$daysToExpire = get_option('daysToExpire');
$live = get_option('live');
$liveVal = $live['menu'];
$easypayIndexPage = '';
if ($liveVal == 'no') {
$easypayIndexPage = 'https://easypaystg.easypaisa.com.pk/easypay/Index.jsf';
} else {
$easypayIndexPage = 'https://easypay.easypaisa.com.pk/easypay/Index.jsf';
}
$merchantConfirmPage = home_url().'/wp-content/plugins/Easypay/confirmEasypay.php';
$options = get_option('autoRedirect');
//$autoRedirect = checked( isset( $options['autoRedirectCb'] ) );
$autoRedirect = checked( isset( $options['autoRedirectCb'] ),1,false );
if($autoRedirect) {
$autoRedirect = 1;
} else {
$autoRedirect = 0;
}
$orderId = $_GET['orderId'];
if (strpos($_GET['amount'], '.') !== false) {
$amount = $_GET['amount'];
} else {
$amount = sprintf("%0.1f",$_GET['amount']);
}
$custEmail = $_GET['custEmail'];
$custCell = $_GET['custCell'];
$hashKey = get_option('hashKey');
date_default_timezone_set('Asia/Karachi');
$expiryDate = '';
$currentDate = new DateTime();
if($daysToExpire != null) {
$currentDate->modify('+'.$daysToExpire.'day');
$expiryDate = $currentDate->format('Ymd His');
}
$paymentMethods = get_option('paymentMethod');
$paymentMethodVal = $paymentMethods['methods'];
$hashRequest = '';
if(strlen($hashKey) > 0 && (strlen($hashKey) == 16 || strlen($hashKey) == 24 || strlen($hashKey) == 32 )) {
// Create Parameter map
$paramMap = array();
$paramMap['amount'] = $amount ;
$paramMap['autoRedirect'] = $autoRedirect ;
if($custEmail != null && $custEmail != '') {
$paramMap['emailAddr'] = $custEmail ;
}
if($expiryDate != null && $expiryDate != '') {
$paramMap['expiryDate'] = $expiryDate;
}
if($custCell != null && $custCell != '') {
$paramMap['mobileNum'] = $custCell;
}
$paramMap['orderRefNum'] = $orderId ;
if($paymentMethodVal != null && $paymentMethodVal != '') {
$paramMap['paymentMethod'] = $paymentMethodVal ;
}
$paramMap['postBackURL'] = $merchantConfirmPage;
$paramMap['storeId'] = $storeId ;
//Creating string to be encoded
$mapString = '';
foreach ($paramMap as $key => $val) {
$mapString .= $key.'='.$val.'&';
}
$mapString = substr($mapString , 0, -1);
// Encrypting mapString
$ivlen = openssl_cipher_iv_length($cipher="AES-128-ECB");
$iv = openssl_random_pseudo_bytes($ivlen);
$crypttext = openssl_encrypt($mapString, $cipher, $hashKey,OPENSSL_RAW_DATA, $iv);
$hashRequest = base64_encode($crypttext);
}
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con) {
die('Could not connect: ' . mysqli_errno());
}
mysqli_select_db($con, DB_NAME);
global $wpdb;
$table_name = $wpdb->prefix . 'easypay_order';
// mysql inserting an order with pending status
$query = "INSERT INTO ".$table_name."( easypay_order_id, easypay_order_info, easypay_order_status, ipn_attr ) VALUES ('$orderId' ,'null', 'pending', 'null')";
try {
mysqli_query($con, $query);
} catch (Exception $ex) {
error_log($ex->getMessage());
}
// echo $easypayIndexPage;
//echo "\r\n".$storeId;
// echo $amount;
//echo $merchantConfirmPage;
//echo $orderId;
// echo $hashRequest;
//<?php header("Location: $easypayIndexPage") ?>
<form name="easypayform" method="post" action="<?php echo $easypayIndexPage; ?>">
<input name="storeId" value="<?php echo $storeId ?>" hidden = "true" readOnly="true" />
<input name="amount" value="<?php echo $amount ?>" hidden = "true"/>
<input name="postBackURL" value="<?php echo $merchantConfirmPage ?>" hidden = "true" readOnly="true" />
<input name="orderRefNum" value="<?php echo $orderId ?>" hidden = "true" readOnly="true" />
<?php if ($expiryDate != '' && $expiryDate != null) { ?>
<input name="expiryDate" value="<?php echo $expiryDate ?>" hidden = "false"/>
<?php } ?>
<input name="autoRedirect" value="<?php echo $autoRedirect ?>" hidden = "true"/>
<input name="emailAddr" value="<?php echo $custEmail ?>" hidden = "true"/>
<input name="mobileNum" value="<?php echo $custCell ?>" hidden = "true"/>
<input name="merchantHashedReq" value="<?php echo $hashRequest ?>" hidden = "true"/>
<input name="paymentMethod" value="<?php echo $paymentMethodVal ?>" hidden = "true"/>
</form>
<script data-cfasync="false" type="text/javascript">
document.easypayform.submit();
</script>
When I click on Proceed to easypay nothing appears on the page and just white black page appears, so after research I came to know that this below written code is not working:
<script data-cfasync="false" type="text/javascript">
document.easypayform.submit();
</script>
Therefore I added this line of code into my form so that I can manually click the button so redirect to EasyPay page.
<input type = "submit" value="Submit">
Now, when clicking on the submit button it is redirecting to EasyPay page but this error occurs saying Parameter Authentication failed.
So, is there anyone who can help me out in this implementation because there support team is not helpful.
I will be very thankful for your help.
This EasyPay plugin can't accept payment values greater than 2 decimals, so, by going in Woo-Commerce plugin in the currency's setting and changing number of decimals to 1 the EasyPay plugin issue will be resolve.
The following code creates two folders, one with the $folderName and one with the $date with the files uploaded. If I change the $folderName to something static like "uploadingFolder" it creates the folder with the files uploaded.
How can I get the naming convention for the folder I want uploaded with its contents: firstname lastname date.
$formdata = json_decode(file_get_contents("php://input"),true);
$fname = array_column($formdata, 'firstname');
$lname = array_column($formdata, 'lastname');
$date = date('d-m-Y');
$folderName = $fname[0].$lname[0].$date;
//$folderName = "uploadingFolder";
mkdir('uploads/'.$folderName, 0777, true);
$total = count($_FILES['files']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
$newFilePath = "uploads/".$folderName."/".$_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)){
echo "upload successful ";
} else {
echo "error uploading files ";
}
}
Sample of json
$sampledata = '{"step":3,"form":{"firstname":"Jackie","lastname":"Hamer","address":"#45 test street","phone":"8681234567","email":"jackie#gmail.com","id":"a0e4c2c2g6c2b1g6","passport":"4545454787T","country":"Grenada","date":"2020-06-13","rdate":"2020-06-11","hotel":"True Blue Bay","package":"10","payment":"10","pfirstname":"Jamie","plastname":"Grant","atravellerfirstname":"Jackie","atravellerlastname":"Browne","refereefname":"Jamie","refereelname":"Lester","refereeaddress":"#45 Test","refereephone":"8684567894","refereefname2":"Jamie","refereelname2":"Louis","refereeaddress2":"#45 Test","refereephone2":"8687878787","formfiles":[]},"countries":[{"Country":"Grenada","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657087,"_created":1591657074,"_id":"5edec27264396144390000cd"},{"Country":"Barbados","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657105,"_created":1591657105,"_id":"5edec2913763637d1700010f"},{"Country":"St. Lucia","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657142,"_created":1591657142,"_id":"5edec2b6303466c0d0000254"},{"Country":"Curacao","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720520,"_created":1591720483,"_id":"5edfba233336352eef0002f9"},{"Country":"Panama","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720527,"_created":1591720527,"_id":"5edfba4f363331fc08000133"},{"Country":"Cancun","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720558,"_created":1591720558,"_id":"5edfba6e38353443d10002c6"}],"hotels":[{"HotelName":"True Blue Bay","URL":"https://www.truebluebay.com/","Country":["Grenada"],"Image":{"path":"storage/uploads\\truebluebay.jpg"},"_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720577,"_created":1589575617,"_id":"5ebeffc134306446460002b9","TestCountry":null}],"selectValue":"Grenada","files":[{},{},{},{},{},{}],"disabled":false,"sumbitted":false,"submitted":true}';
Like this;
<?php
$formdata = json_decode(file_get_contents("php://input"), true);
$fname = $formdata['form']['firstname'];
$lname = $formdata['form']['lastname'];
$date = date('d-m-Y');
$folderName = $fname.' '.$lname.' '.$date;
// Added spaces between for ya. Would recommend to do it like [YYYY-MM-DD Lastname Firstname] though
mkdir('uploads/'.$folderName, 0777, true);
$total = count($_FILES['files']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
$newFilePath = "uploads/".$folderName."/".$_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)){
echo "upload successful ";
} else {
echo "error uploading files ";
}
}
I did an test on this;
<?php
$sampledata = '{"step":3,"form":{"firstname":"Jackie","lastname":"Hamer","address":"#45 test street","phone":"8681234567","email":"jackie#gmail.com","id":"a0e4c2c2g6c2b1g6","passport":"4545454787T","country":"Grenada","date":"2020-06-13","rdate":"2020-06-11","hotel":"True Blue Bay","package":"10","payment":"10","pfirstname":"Jamie","plastname":"Grant","atravellerfirstname":"Jackie","atravellerlastname":"Browne","refereefname":"Jamie","refereelname":"Lester","refereeaddress":"#45 Test","refereephone":"8684567894","refereefname2":"Jamie","refereelname2":"Louis","refereeaddress2":"#45 Test","refereephone2":"8687878787","formfiles":[]},"countries":[{"Country":"Grenada","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657087,"_created":1591657074,"_id":"5edec27264396144390000cd"},{"Country":"Barbados","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657105,"_created":1591657105,"_id":"5edec2913763637d1700010f"},{"Country":"St. Lucia","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657142,"_created":1591657142,"_id":"5edec2b6303466c0d0000254"},{"Country":"Curacao","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720520,"_created":1591720483,"_id":"5edfba233336352eef0002f9"},{"Country":"Panama","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720527,"_created":1591720527,"_id":"5edfba4f363331fc08000133"},{"Country":"Cancun","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720558,"_created":1591720558,"_id":"5edfba6e38353443d10002c6"}],"hotels":[{"HotelName":"True Blue Bay","URL":"https://www.truebluebay.com/","Country":["Grenada"],"Image":{"path":"storage/uploads\\truebluebay.jpg"},"_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720577,"_created":1589575617,"_id":"5ebeffc134306446460002b9","TestCountry":null}],"selectValue":"Grenada","files":[{},{},{},{},{},{}],"disabled":false,"sumbitted":false,"submitted":true}';
$formdata = json_decode($sampledata, true);
$fname = $formdata['form']['firstname'];
$lname = $formdata['form']['lastname'];
$date = date('d-m-Y');
$folderName = $fname.' '.$lname.' '.$date;
var_dump($folderName); // string(23) "Jackie Hamer 16-06-2020"
Extra important note: Be sure no illegal chars for folders exists in the first or lastname ! You should strip or replace illegal special chars!
Everyone.
I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here. Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button. The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.) Right now, the code doesn't even seem to return success or failure messages.
Here's the script on the main page:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var RID=$("#RID").val();
var Services=$("Services").val();
var Dues_List=$("Dues_List").val();
var ID=$("ID").val();
var myrid=$("myrid").val();
var Manager_Comments=$("Manager_Comments").val();
var President_Comments=$("President_Comments").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
$.ajax({
type: "GET",
url:'baseupdater-test.php' + dataTosend,
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
});
</script>
Here's the code that draws the rows on the table:
<?php
/* This code writes the rows in the table for baserecord.php */
$n = 0;
$o = $n + 1;
$firstday = date('m/1/Y');
if(isset($_GET['MR'])) // If $_GET['MR'] is set ...
{
$MR = $_GET['MR']; // Set the variables.
$PR = $Pres_Rev;
}
else // If not, select the maximum (latest) Manager Review Date.
{
$getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
President_Review_Date from clientdb.MRS2_test
inner join clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where SCID = '$ID';";
$rs2 = mysqli_query($con,$getmr);
$rvd = mysqli_fetch_assoc($rs2);
$MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
echo "MR: $MR<br>";
$PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}
// The following query select the data for the row and orders it by the latest Manager Review Date.
$cliselect = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
from clientdb.Plans
inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";
//echo "cliselect $cliselect<br>";
$cres = mysqli_query($con, $cliselect);
while ($dddr = mysqli_fetch_assoc($cres)) {
$DDD_Case = $dddr['DDD_Case'];
$First_Name = $dddr['First_Name'];
$Last_Name = $dddr['Last_Name'];
$County = $dddr['County'];
$Tier = $dddr['Tier'];
if($ddr['Plan_End_Date'] <> '')
{
$Plan_End_Date = $dddr['Plan_End_Date'];
}
$Pres_Comments = $dddr['President_Comments'];
$Mgr_Comments = $dddr['Manager_Comments'];
$Dues = $dddr['Dues_List'];
$Services = $dddr['Services_Issues'];
$RID = $dddr['RID'];
$mxselect = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
$rens = mysqli_query($con, $mxselect);
$rmm = mysqli_fetch_assoc($rens);
$MPlan = $rmm['MPlan'];
$endsel = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
$rsel = mysqli_query($con, $endsel);
$end = mysqli_fetch_assoc($rsel);
$Plan_End_Date = $end['Plan_End_Date'];
$Program = $end['Program'];
//The purpose of ths quer s to get the RID for each row.
$mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
group by DDD_Number, RID
order by RID DESC
Limit 1 ;";
$run = mysqli_query($con,$mrselect);
$mrss = mysqli_fetch_assoc($run);
$Manager_Review_Date = $mrss['Manager_Review_Date'];
$President_Review_Date = $mrss['President_Review_Date'];
$myRID = $mrss['RID'][$n];
echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
?>
<?php echo strtotime($Plan_End_Date);
echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";
$n = $n++;
$o++;
}
?>
And finally, this is the code that does the update:
<?php
include 'config.php';
$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);
$Manager_Review = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";
if($_GET['President_Review'] == '12/31/1969')
{
$President_Review = '';
}
if($_GET['President_Review'] <> '')
{
$President_Review = $_GET['President_Review'];
}
else
{
$President_Review = '';
}
$ID = $_GET['ID'];
$Services = $_GET['Services'];
echo "New Content!<br>";
$n = 0;
while ($n <= sizeof($_GET)) {
$ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
inner join clientdb.clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
order by RID;";
$rsc = mysqli_query($con, $ridselect);
$rowrid = mysqli_fetch_assoc($rsc);
$RID = $_GET['myrid'][$n];
// echo "RID: $RID<br>";
$MDD = $_GET['RID'];
$myrid = $_GET['myrid'][$n];
$DDD_Case = $_GET['DDD_Number'][$n];
$Period = ltrim(substr($Manager_Review,0,2), "0");
$Services = mysqli_real_escape_string($con, $_GET['Services'][$n]);
$Manager_Comments = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
$President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
$Dues_List = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
$DDD_Case = $_GET['DDD_Number'][$n];
$updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";
$date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
echo "dateupdater: $date_updater<br>";
if(!mysqli_query($con, $date_updater))
{
echo "That failed miserably.<br>";
}
else
{
$rws = mysqli_affected_rows($con);
echo "affected rows: $rws<br>";
echo "Success.<br>";
}
mysqli_query($con, $updater);
$datestamp = date('Y-m-d h:i:s');
$upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
mysqli_query($con,$upstamp);
$n++;
}
echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";
?>
I've tried serializing the form, and I haven't had any success there. Any suggestions would be greatly welcome. Sorry for the long post, but I'm just not sure where the error is at this point.
Your code
var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.
And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.