You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:如何对比MySQL数据库Float类型字段与输入变量值

Hey there! Let's work through fixing your code—you've got a few critical issues that are preventing the fund check from working correctly.

Key Problems in Your Current Code

  • You're comparing a result set to a boolean: mysqli_query() returns a result set object, not the actual mon value from your database. You need to fetch the value from this result set first.
  • Incorrect use of isset(): isset($_POST['mon']) returns true or false (a boolean), not the value of the input. You can't compare a boolean to a database result set directly.
  • SQL injection vulnerability: Directly interpolating $user_id into your SQL query is a huge security risk. Always use prepared statements for database queries that include user-supplied values.

Fixed Code Example

// First, check if the form was submitted and the 'mon' input exists
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mon'])) {
    // Sanitize and convert the input to a float
    $input_amount = (float)$_POST['mon'];

    // Use a prepared statement to avoid SQL injection
    $stmt = mysqli_prepare($conn, "SELECT mon FROM users WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $user_id); // "i" means integer type for $user_id
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $db_amount);
    mysqli_stmt_fetch($stmt);
    mysqli_stmt_close($stmt);

    // Now compare the two float values
    if ($input_amount > $db_amount) {
        $results = "<div class='alert alert-danger alert-dismissible'>
            <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
            <strong>Error!</strong> Not enough Funds!
        </div>";
    }
}

Additional Notes

  • Always validate user input: You might want to add checks to make sure $_POST['mon'] is a valid number (e.g., using is_numeric()) before converting it to a float.
  • Handle cases where no user is found: If the $user_id doesn't exist in the users table, $db_amount will be undefined. You should add a check for that (e.g., if (isset($db_amount)) before the comparison).

内容的提问来源于stack exchange,提问作者Bunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:32:21