Balance transferring transaction - PHP and MySQL - php

I'm in a middle of a project and I need to create a page in which the user account will be able to transfer a certain amount of "money" to another registered account.
After the transfer action ends, I need to have a transcript of the transaction.
I created a new DB that contains all the transactions but I can't figure out how to call the data.
I tried to use this in the api.php:
`//get all transactions
case "get_all_transactions":
$cursor = $MySQLdb->prepare("SELECT * FROM transactions");
$cursor->execute();
$retval = "";
foreach($cursor->fetchAll() as $row){
if ($row["send_account"] == $user OR $row["recive_account"] == $user){
$retval = retval . "<br>"echo .$row['send_account']."<br>".$row['recive_account']."<br>".$row['amount'];
}else{
$msg = "nope";
}
}
echo '{"success":"true","data":"'.$retval.'"}';
die();
break;`
I add this in the transaction.php page:
//get all transactions
$.post("api.php",{"action":"get_all_transactions"},function(data){
if(data.success == "true"){
$("#transactions_history").html(data.data);
}
});
I can't figure out how to continue.
Can anyone assist, please?
If you have any other way, it will be great.
Thanks!

Related

How to trigger an event in Laravel when nothing has been added to the database versus being alerted to when it has been updated?

I am building a simple auction solution on Laravel. The below code is some extract test code that is suppose to act as the auctioneer.
The problem is that when it's running it locks up access to the Auctionbid Postgres table and users can't bid while it's running. My testing is on localhost running a few users in auction as well as the auctioneer process all on same box/same IP<--might be making issue worse (not sure).
I've read all about the issues on SO about sleep(), downsides of polling and PHP sessions and have dug into Websockets a bit to see if I should go there. It also would also allow me to replace Pusher.
However, the issue I see is that an auction is all about timing and what events are NOT happening (if no bid in 3 seconds tell users "Fair Warning") and the Websocket implementations I've read about seem to be about what events ARE happening.
Questions:
Would a websockets implementation possibly be a solution? Every article I've looked at seems to be about the events that ARE happening. Maybe the classes on negative space are hindering my ability to see the solution :-)
Is having this all run on the same box/IP the issue? And/Or is sleep() just a bad way moving forward - as pointed out in at least 100 SO posts...
What are other possible solutions that allow me to check for what events are NOT happening?
public function RunTheAuction($auction_item_id, $auction_id)
{
set_time_limit(300);
$options = array(
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true
);
$pusher = new Pusher(
env('PUSHER_APP_KEY'),
env('PUSHER_APP_SECRET'),
env('PUSHER_APP_ID'),
$options
);
$bidIncrementResetCounter = 0;
$lastBidderId = 0;
$currentWinnerBidAmount = 0;
$lastBidderBidAmount = 0;
$count = 0;
while(true){
$auctionbid = Auctionbid::select('id', 'bid', 'bid_timestamp', 'auction_bidder_id')
->where('auction_item_id', '=', $auction_item_id)
->where('auction_id', '=', $auction_id)
->orderBy('bid', 'desc')
->orderBy('bid_timestamp', 'asc')
->first();
if ($auctionbid) { //there is a bid on the item
$currentWinnerId = $auctionbid->id;
$currentWinnerBidAmount = $auctionbid->bid;
if (($lastBidderId == $currentWinnerId) && ($lastBidderBidAmount == $currentWinnerBidAmount)) { //it's the same bidder
if ($bidIncrementResetCounter == 1) {
$message = "Fair Warning!";
$pusher->trigger('bids_channel', 'bid-warning', $message);
}
if ($bidIncrementResetCounter == 2) {
$message = "Going once... Going twice...";
$pusher->trigger('bids_channel', 'bid-warning', $message);
}
if ($bidIncrementResetCounter == 3) {
$message = "We have a winner!";
$pusher->trigger('bids_channel', 'bid-warning', $message);
break;
}
$bidIncrementResetCounter++;
} else {
$bidIncrementResetCounter = 0;
}
}
else{
$currentWinnerId = 0;
}
$lastBidderId = $currentWinnerId;
$lastBidderBidAmount = $currentWinnerBidAmount;
sleep(10); //<-----------------------------ISSUE
$count++;
if($count == 12){break;}
} //end loop
} //end function RunTheAuction

PHP Page is posting multiple times occasionally

I have a registration form which posts data to save.php. But occasionally the data is getting posted multiple times.
Below is my code for save.php
<?php
session_start();
//save registration details in my table
include('connect_database.php');
include('my_functions.php');
$_SESSION['newUser'] = '0'; // new user
//POSTED DATA--------------------------
$t_email = $_POST['email'];
$t_psw = $_POST['psw'];
$t_first_name = addslashes($_POST['first_name']);
$_SESSION['lastname'] = $t_last_name = addslashes($_POST['last_name']);
$t_mobile = $_POST['mobile'];
$_SESSION['licNum'] = $t_lic_no = $_POST['lic_no'];
$t_dob = $_POST['dob'];
$t_abn = $_POST['abn'];
$tx_expiry = $_POST['tx_expiry'];
$drv_for = $_POST['driven_for'];
$lng_drv = $_POST['long_driven'];
//referred by
$ref_drLic = $_POST['ref_driLic'];
$ref_drName = $_POST['ref_driName'];
$t_dr_front = get_image('dr_front',$_POST['last_name'].'_dr_front');
$t_dr_bck = get_image('dr_bck',$_POST['last_name'].'_dr_bck');
//if tx required-------
if($_SESSION['ce_cr_tx'] == 1){
$t_tx_front = get_image('tx_front',$_POST['last_name'].'_tx_front');
$t_tx_bck = get_image('tx_bck',$_POST['last_name'].'_tx_bck');
}
else{
$t_tx_front = "";
$t_tx_bck = "";
}
//store data in logfile
$nwtxt = "Email is - ".$_POST['email'].". Mobile no - ".$_POST['mobile'];
writeFile($nwtxt);
//---------------------------------------
//query to save data in my table
$ad_sql = "INSERT INTO myTable (email, password, firstname, lastname, mobile, licence, drfront, drbck, txfront, txbck, cnfrm, dob, abnf, texpiry, drifor, driven, reLic, reNname)
VALUES('".$t_email."','".$t_psw."','".$t_first_name."','".$t_last_name."','".$t_mobile."','".$t_lic_no."','".$t_dr_front."','".$t_dr_bck."','".$t_tx_front."','".$t_tx_bck."','0','".$t_dob."','".$t_abn."','".$tx_expiry."','".$drv_for."','".$lng_drv."','".$ref_drLic."','".$ref_drName."')";
if(!empty($t_email)){
if($conn->query($ad_sql) == true){
//echo'Success';
$lst_id = $conn->insert_id;
$_SESSION['ls_id'] = $lst_id;
$_SESSION['s_email'] = $t_email;
$_SESSION['s_code'] = mt_rand(11111,99999);
//email code to user--------------------------
$subjct = "Email Verification Code";
$usr_msg = "Hi ".$_POST['first_name']." ".$_POST['last_name'].",<br><br>
A new account has been requested at 'Portal'
using your email address.<br><br>
To confirm your new account, please enter this code in the web page:<br>
<h3>".$_SESSION['s_code']."</h3><br><br>
If you need help, please call us<br><br>
Thank you,
Administrator";
sendEmail($t_email, $usr_msg, $subjct); //sends and email
writeFile('Code is :'.$_SESSION['s_code']); // write a log in file
//--------------------------------------------
//redirect to verify email page----------------------
header("location: verifyEmail.php");
exit();
}
else{
echo'Error creating account- '.$conn->error.'. Please try again.';
$gbck = "cr=".$_SESSION['ce_cr_id']."&crs=".$_SESSION['ce_cr_nm']."&tx=".$_SESSION['ce_cr_tx']."&erms=Error creating account. Please try again";
header('location: Enroll.php?'.$gbck);
exit();
}
}
else{
echo'Error creating account. Please try again.';
$gbck = "cr=".$_SESSION['ce_cr_id']."&crs=".$_SESSION['ce_cr_nm']."&tx=".$_SESSION['ce_cr_tx']."&erms= EMPTY data. Error creating account. Please try again";
header('location: Enroll.php?'.$gbck);
exit();
}
?>
I checked my code multiple times but couldn't find anything that is triggering it. When someone registers, the page keeps loading for sometime and I receive multiple entries in database and user receives multiple verification emails.
Is something wrong in my code?
The code itself looks fine, but i get the growing suspicion that it might be a config issue or whats happening before this executes. If your looking for a patchwork fix i would probably put a condition near your if(!empty($t_email)) that checks if the sql table row already exists dont execute, which would rectify the fact that multiple requests are coming in.

I am not successful with PayPal-PHP-SKD code "payment->execute"

I have successfully utilized PayPal-PHP-SKD to request a payment sending the user to the PayPal payment gateway sandbox with credentials and sandbox buyer account etc. Everything works and I get a request to the returnURL with $_GET variables success=true, paymentID, token and PayerID. My problem is in the next step which captures the paymentID and PayerID, creates objects for Payment PaymentExecution which seems to work OK but crashes when I execute the line "result = $payment->execute($exClaimPayment, $mPPcredentials);". If I comment out that line, the code works without error but when I include it the code crashes.
"result = $payment->execute($exClaimPayment, $mPPcredentials);"
if (isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])) {
if ($_GET['success'] == 'true') {
$mSuccess = TRUE;
$mPaymentID = $_GET['paymentId'];
$mPayerID = $_GET['PayerID'];
$payment = Payment::get($mPaymentID, $mPPcredentials);
$exClaimPayment = New PaymentExecution();
$exClaimPayment->setPayerId($mPayerID);
$mProgress = 'in success after $exClaimPayment->setPayerId($mPayerID)';
try {
$mProgress = 'in try';
//result = $payment->execute($exClaimPayment, $mPPcredentials);
} catch(Exception $ex){
$errorMsg = json_decode($ex->getData());
}
}
} else {
$mSuccess = FALSE;
$mProgress = 'in NOT success';
}
In my envoronment, Win 10, Notepad++, FileZilla, Hostmonnster hosting and Chrome, I cannot see the error. It just crashes (with HTTP 500 ??)
I found my error! It was MY error.
The line:
result = $payment->execute($exClaimPayment, $mPPcredentials);
Should have been:
$result = $payment->execute($exClaimPayment, $mPPcredentials);
I have worked on this code for half a day and did not see my error until 5 minutes after I posted the question on StackOverflow.
My conspicuous errors in PHP often cost me a lot of time. I would benefit from an environment that would point out my syntax errors.
StackOverflow is a very good resource. Thanks!

Filemaker via PHP

I am working on a php script that gets the values of the fields inside a Filemaker database. What I want to accomplish now is how do I edit/update the field values of each field to new values and should be saved in the Filemaker database. This is my code in getting the field:
require_once ('../../FileMaker.php');
$fm = new FileMaker('dataStest.fp7', 'https://secure.smartdecision.org', 'web', 'webtest');
$findCommand = $fm->newFindCommand('List');
$findCommand->addFindCriterion('ID1',$ftype);
$result = $findCommand->execute();
$records = $result->getRecords();
foreach ($records as $record) {
if ($record->getField('ID3') == "ACTIVE" && $record->getField('ftyCat') == "treatment") {
echo $record->getField('d15'). '<br>';
}
If(FileMaker::isError($result)){
echo "Could not connect to the field";
}
Any suggestions would be very helpful. Thank you!
You just need to use the setField method as documented in the FileMaker PHP API (here's the page for the documentation on the FileMaker_Record class) and then commit your record with commit:
...
$record->setField('d15', 'new value');
$record->commit();
...

Unknown Error on Web Host but code runs well on localhost

I just had finished a form working in my localhost, it was working perfectly, but by the time I uploaded the code to the web host it wasn't working as it was supposed to. It is a simple form that uses PHP, MySQL and JQuery. When I click on submit it shows my custom error window saying that the email was registered already but the thing is that the database is empty. I put some code inside the ajax part that checks the email and this is what it says (it's supposed to show only a number):
Warnings : mysql_fetch_assoc(): supplied argument is not a valid MySQL result resources in /*/*/public_html/check_user.php on line 17
Here's check_user.php:
<?php
require_once("SqlChromoConnection.php");
// Check if email is not empty in the form
if(isset($_POST['email'])) {
// create the query
$sql = "SELECT COUNT(*) AS count
FROM Users
WHERE email = '" . trim($_POST['email']) . "'";
// create object to handle the connection
$conn = new SqlChromoConnection();
$conn->getDatabaseConnection(); // establish a connection
$data = $conn->executeQuery($sql); // execute query
$count= mysql_fetch_assoc($data); // save result in $count
$exists = $count['count']; // access only the field 'count'
$conn->closeConnection(); // close the connection
echo $exists;
exit(0);
}
?>
And here's the ajax part that checks the email:
if( !re.test(email) || email.indexOf(' ') > 0) {
message = "Email NOT valid!!!";
messageDialog("Warning", message, "warning", 2);
return false;
} else {
// use ajax to check if a user has been previously registered
// using this email
var valid = false;
$.ajax(
{
url:"check_user.php", // url that will use
async: false,
data:{ // data that will be sent
email:email
},
type:"POST", // type of submision
dataType:"text", // what type of data we'll get back
success:function(data)
{
window.alert(data);
// if check_user returns 0
// means that there's no any user registered with that email
if(data == 0 ) {
valid = true;
}
}
});
if(!valid) {
message = "This email is registered already!";
messageDialog("Error", message, "error", 2);
return false;
}else return true;
}
As I said, the code runs well when in localhost.
Any suggestions will be really appreciated.
Regards.
Add # before your mysql_fetch_assoc it removes all warning comes from this statement.
Use like #mysql_fetch_assoc().
I think you should use users Instead of Users for table name

Categories