dpz3471 2017-12-29 13:32
浏览 48
已采纳

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

ı 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?

  • 写回答

1条回答 默认 最新

  • doubipiao1611 2017-12-29 13:49
    关注

    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';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?