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 actualmonvalue from your database. You need to fetch the value from this result set first. - Incorrect use of
isset():isset($_POST['mon'])returnstrueorfalse(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_idinto 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'>×</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., usingis_numeric()) before converting it to a float. - Handle cases where no user is found: If the
$user_iddoesn't exist in theuserstable,$db_amountwill be undefined. You should add a check for that (e.g.,if (isset($db_amount))before the comparison).
内容的提问来源于stack exchange,提问作者Bunny
相关产品推荐
相关产品推荐

