0

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.

3
  • if the exp is numeric you should avoid the single quotes around $xp in query and assing a numeric value to $xp Commented Mar 7, 2017 at 18:30
  • Remove the quotes around 500 in $xp = 500; Commented Mar 7, 2017 at 18:31
  • it returns Rank3 even though the $xp is 450 Commented Mar 7, 2017 at 18:55

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't remove the ) at the end of the query line. Come on you should've picked up on that :P
0

You did put single quotes around $xp in the query, but it is probably a numeric value, not a string. Now you are probably comparing a numeric value with a string. Try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.