PHP如何从数据库更新会话?

时间:2017-12-29 13:32:40

标签: php session

我想更新我的会话变量这段代码:

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;
}

我使用$_SESSION['kazanc'] = $row["kazanc"];方法从我的数据库mysqli_fetch_array获取变量。如何从数据库更新我的会话kazanc变量?

1 个答案:

答案 0 :(得分:0)

在尝试使用它们之前,您应该检查实际存在的会话变量,当您进行乘法时,请确保将数字乘以数字和字符串的混合。此外,为了避免SQL注入,请使用prepared statements作为用户输入预期或可能的用途。

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';
    }
}