PHP how to update a session from database?


ı 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"]; usingmysqli_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 useprepared 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';

People are also looking for solutions to the problem: php - jQuery AJAX method not working


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.