ı want to update my session variable this code:
if (isset($_POST['topla'])) {
$kazanc_cow = $_SESSION['cow'] * "0.003";
$kazanc_chicken = $_SESSION['chicken'] * "0.001";
$db_kazanc = $_SESSION['kazanc'];
$toplam_kazanc = $db_kazanc + $kazanc_chicken + $kazanc_cow;
$uid = $_SESSION['user_id'];
$sql = "UPDATE users SET kazanc='$toplam_kazanc' WHERE id='$uid'";
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
I am get variable from my database $_SESSION['kazanc'] = $row["kazanc"];
using mysqli_fetch_array
method. how ı update my session kazanc variable from database?
You should check the session variables actually exist before trying to work with them and when you are multiplying make sure you multiply numbers not a mix of numbers and strings. Also, to avoid SQL injection use prepared statements
as a matter of course where user input is expected or possible.
if ( isset( $_POST['topla'], $_SESSION['cow'], $_SESSION['chicken'], $_SESSION['kazanc'], $_SESSION['user_id'] ) ) {
$kazanc_cow = floatval( $_SESSION['cow'] ) * 0.003;
$kazanc_chicken = floatval( $_SESSION['chicken'] ) * 0.001;
$db_kazanc = floatval( $_SESSION['kazanc'] );
$toplam_kazanc = $db_kazanc + $kazanc_chicken + $kazanc_cow;
$uid = $_SESSION['user_id'];
$sql='update `users` set `kazanc`=? where `id`=?';
$stmt=$con->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ss', $toplam_kazanc, $uid );
$result = $stmt->execute();
echo $result ? 'Record updated successfully' : 'Error updating record';
}
}