douduandiao1368 2017-03-07 18:27
浏览 34
已采纳

找到一个值大于或等于给定数字的行(mysql)

I'm creating a rank system and ranks are stored in a database, my problem is about finding rows with greater or equal value to given user xp:

It's something like this:

list of ranks in ranks table:

name: Rank1 exp: 400

name: Rank2 exp: 500

name: Rank3 exp: 700

$xp = "500";

$find = $db->query("SELECT * FROM ranks WHERE exp >= '$xp' LIMIT 1");

if($find->num_rows > 0){
 // if a rank with greater than or equal value was found
  $rdata = $find->fetch_assoc();
 // return rank name
  echo $rdata["name"];
}

this returns Rank1, i don't know why :(

Can anyone help me? I'm not yet good in mysql.

  • 写回答

2条回答 默认 最新

  • duanna5749 2017-03-07 18:33
    关注

    Remove the " " around 500, but for future reference I'd turn this into a prepared statement as your query isn't as secure as it could be

    $xp = 500;
    
    $query = "SELECT name FROM ranks WHERE exp >= ?' LIMIT 1";
    $stmt = $db->prepare($query);
    $stmt->bind_param("s",$xp);
    $stmt->execute();
    $stmt->bind_param($name);
    while($stmt->fetch()){
       if($stmt->num_rows > 0 ){
          echo $name;
        }
    }
    

    Another suggestion. Instead of selecting where >= $xp and limiting by 1, Why not select the range you're actually looking for? between 500 and 700 so it doesn't bring back 700?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度