1

I am passing the number 1 from my javascript file as $played = json decode. I am not sure my Select query is working correctly, or my math is just all wrong. PHP is still new to me and I'm not sure if I can rename strings, and still have the query work. I know everything has to be passed into PHP to work and that I cant just make a variable and bind it and have the update work. I was thinking I could rename my passed JSON string so it could be used temporarily, but then I figured I could just name my SELECT string $results and then add the two.

The problem I am having is, it appears to UPDATE twice to the database. No matter how many times I wager, my database only shows the number 2. It's like it stops counting and UPDATE.

Any advice is welcome, thank you in advance for looking and helping if you can.

Okay this didn't work. Maybe I'm not understanding the answer. It didn't post anything to the database. Do I still need to bind the values, or no?

   <?php 
session_start();
if(empty($_SESSION['userid']))
{
    header("Location: ../login/index.php");
}
include('../../login/database.php');

if (isset($_SESSION['userid']))
 $played = json_decode(file_get_contents('php://input'), true);
 $userid = $_SESSION['userid'];

try {
$db = DB();

$stmt = $db->prepare("UPDATE usersystem SET played = played + :played WHERE userid = :userid");
$stmt->bindValue(':played', $played, PDO::PARAM_STR);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();

}
catch(PDOException $e)
{
    $db = null;  
    echo $e->getMessage();  
}
}

echo $_POST['package']; 
?>

And here is the javascript POST

    function updateDatabase() { 
    played = 1;
        var package = played;
        //console.log(package);
        fetch('../php/played/played.php', {
          method: 'POST',
             headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
          body: JSON.stringify(package)
        });
}

This is getting aggravating. I have this Version information: 4.6.4 , latest stable version: 4.9.7 phpmyadmin.

Since my played.php will not post the data to the database I decided to use my credit.php file to test the played entry I am trying to make. Here is how I tested it, and this too does not post the info to my database, but my credits do get posted into the database.

credits.php

    <?php 
session_start();
if(empty($_SESSION['userid']))
{
    header("Location: ../login/index.php");
}
include('../../login/database.php');

if (isset($_SESSION['userid'])) {
 $money = json_decode(file_get_contents('php://input'), true);
 $money_as_number = intval( $money );
 $userid = $_SESSION['userid'];
try {
$db = DB();

//$a = 1;
//$db->query("update usersystem set played=played+". intval($a) ."WHERE userid=:userid");
$db->query("UPDATE usersystem set played = played + 1 WHERE userid=:userid");

$stmt = $db->prepare("UPDATE usersystem SET money=:money WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_STR);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();

}
catch(PDOException $e)
{
    $db = null;  
    echo $e->getMessage();  
}
}

echo $_POST['package']; 
?>

Here is my money Ajax which is identical to the played ajax

    var package = money;
//console.log(package);
fetch('../php/credits/credit.php', {
  method: 'POST',
     headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
  body: JSON.stringify(package)
});

Maybe I can't do played = played + with my version? Any ideas?


I solved it finally !!! Thank you very much for answering and educating. Your answer led me to the research i needed so I could understand things better and let me tell you, no more query for me, and have a way better understanding of fetch and how it's used!

    <?php 
session_start();
if(empty($_SESSION['userid']))
{
    header("Location: ../login/index.php");
}
include('../../login/database.php');

if (isset($_SESSION['userid'])) {
 $money = json_decode(file_get_contents('php://input'), true);
 $money_as_number = intval( $money );
 $userid = $_SESSION['userid'];
try {
$db = DB();

$stmt = $db->prepare("SELECT played FROM usersystem WHERE userid=?");
$stmt->execute([$userid]);
$played = $stmt->fetchColumn();

$results = 1;
$played = $results + $played;


$stmt = $db->prepare("UPDATE usersystem SET money=:money, played=:played WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_INT);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->bindValue(':played', $played, PDO::PARAM_INT);
$stmt->execute();

}
catch(PDOException $e)
{
    $db = null;  
    echo $e->getMessage();  
}
}

//echo $_POST['package']; 
?>
Ed Nolan
  • 62
  • 7
  • How do you call your program? Through a URL? Just wondering about this line `$played = json_decode(file_get_contents('php://input'), true);`. Is `$played` an interger at this point? – waterloomatt Nov 10 '20 at 03:03
  • yes, its an interger. That part works fine. I actuall did notice that if I make one wager, it posts the number two. So maybe I am adding wrong. It should have just posted 1 for the one wager. – Ed Nolan Nov 10 '20 at 03:18
  • Can we assume you call your program via the POST method? Can you give us a sample payload of what the request body looks like? Edit your question with this info, don't post it in the comments. Thx. – waterloomatt Nov 10 '20 at 03:31
  • Your final edit looks OK to me, as long as the `$userid` variable is populated and also exists in the DB. Assuming you have `session_start()` above all this. Can you please also turn on error reporting https://stackoverflow.com/a/21429652/296555. Is your try/catch just truncated in the question or is that the final code? – waterloomatt Nov 10 '20 at 04:13
  • sorry I should have put the entire code. I will make sure to do that from now on. I edited it again. – Ed Nolan Nov 10 '20 at 04:29
  • Looks to me your `$db` object is just a wrapper around a PDO connection. If that's true, can you please ensure your connection is set up to throw exceptions. See `$options` here: https://phpdelusions.net/pdo#dsn. Also, turn on error reporting like so https://stackoverflow.com/a/21429652/296555. I think you'll see that your 2nd example throws an exeption because you need to bind/execute once for each update statment. – waterloomatt Nov 10 '20 at 13:59
  • function DB() { try { $db = new PDO('mysql:host='.HOST.';dbname='.DATABASE.'', USER, PASSWORD); return $db; } catch (PDOException $e) { return "Error!: " . $e->getMessage(); die(); } } ?> – Ed Nolan Nov 11 '20 at 03:51
  • Im also looking into simple PDO functions. But if I understand you, are you saying that maybe the connection is the issue? I posted the connection code for you to review. – Ed Nolan Nov 11 '20 at 03:52
  • I also must admit I am on a free server right now and error reporting is off. I'm sorry. The hope is to pay for server once I finish everything. I'm sorry I know it would most likely help but its what I have to do for now. I appreciate your help though. – Ed Nolan Nov 11 '20 at 03:55
  • I finally got the prepared statement correct but still the same issue where the math only triggers once no matter the number of times the php fie is triggered by same user/player. – Ed Nolan Nov 11 '20 at 04:22
  • //$results = $db->query("SELECT played FROM usersystem WHERE userid=:userid"); $stm = $db->prepare("SELECT played FROM usersystem WHERE userid=:userid"); $results = $stm->fetch(); – Ed Nolan Nov 11 '20 at 04:22
  • Error reporting can be done directly in PHP code. Just copy/paste the 3 lines from https://stackoverflow.com/a/21429652/296555 and also make sure to set up your DB connection as https://phpdelusions.net/pdo#dsn (pass in those _$options_). This will ensure any MySQL errors are passed down to PHP and then PHP will display them. All this is done in code; not in PHP ini file. – waterloomatt Nov 11 '20 at 14:25

1 Answers1

0

You can totally do this in a single UPDATE statement without the need for using a SELECT statement.

You can increment the stored value by whatever $played is, by simply:

UPDATE usersystem SET played = played + :played WHERE userid = :userid

And remove that foreach statement. Not sure what your intention is there but it is grabbing the final row of user data whose userid is sorted descending.

Also, $played = json_decode(file_get_contents('php://input'), true); is very suspicious to me. Are you sure $played is an integer at this point? json_decode(..., true) will give you an array. I think you need to fix this before moving forward.

waterloomatt
  • 3,134
  • 1
  • 16
  • 21
  • ahh, okay. Thank you. Let me try this! – Ed Nolan Nov 10 '20 at 03:19
  • $played is an integer – Ed Nolan Nov 10 '20 at 03:28
  • Okay, so you have me wondering about the array. My understanding is that it comes over as $_POST['package']; and then the json_decode returns it as a string. Am I wrong? You have me thinking I am, however when I wager, my credit script looks similar to the above except I am not adding, I am just updating the balance of the credits into the database and it's being posted into the database no matter how many times I wager so my thinking is that it's not an array or it would not be posting into the database. Anyway I'm still stuck here. – Ed Nolan Nov 10 '20 at 04:19
  • I think you can assume you ARE receiving an integer if you are posting the single value of `1`. If you post a JSON object instead then you will get an array. See this example. http://sandbox.onlinephpfunctions.com/code/e32b4a1e0c996aed57ef73beb14e4c3ed51b88e9 – waterloomatt Nov 10 '20 at 14:35