Home > other >  updating a database more then once php
updating a database more then once php

Time:06-20

I have a total amount. when i sell an item i want to add that amount to my total. e.g i have 100.00, i sell a snake for 100.00 so my total should be 200.00. I have it working so it adds the 100.00 but if i want to sell two snakes it will stay at 200.00 it won't add any amount from the second snake. using this to update my database.

if(isset($_POST['go'])
{ 
     $query = "UPDATE  users  SET amount=$current WHERE email = '".$_SESSION['email']."'";
}
if(isset($_POST['go'])      //edit 17.06.2022
{  
      $current = $amount 100;
}

CodePudding user response:

  1. You need to do the calculation before you use the calculated amount, which is $current
  2. You need to execute the sql statement
if(isset($_POST['go'])
{
 $current = $amount 100;
 $query = "UPDATE  users  SET amount=$current WHERE email ='".$_SESSION['email']."'";
$result=$db->exec($query);
}  
      

$db is from the connection file below

<?php

  $db=new PDO('mysql:host=localhost;dbname=testdb;charset=utf8','root','');
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
?>

Add the below line before interacting with the DB.

require('connection.php');

When you get it to run, I suggest looking at prepared statements to prevent SQL injection vulnerabilities on your app

CodePudding user response:

Your code runs in order, so changes made to $current after you've run the SQL won't be saved anywhere, they'll just be thrown away at the end of the current request.

If you want to update the value in the database, you need to move the calculation to before the SQL query.

  • Related