0

可能重复:
MYSQL PHP - get float LIKE $float

我有来自数据库的浮点数。这是我的代码:

$float = $_GET['float'];
$requst = mysql_query("SELECT * FROM floats WHERE float LIKE'$float.%%%%%%%' AND float2 LIKE'$float2.%%%%%%%'");
while ($r = mysql_fetch_array($requst)) {

    $array[] = $r['float'];

}

代码从用户名中获取浮点数$float并从数据库中的表中浮点数并将其添加到数组中。

我怎么知道数组中的浮点数接近$float

4

1 回答 1

0
// Lets cast provided float to float type to prevent sql injections
$float = (float) $_GET['float'];
$requst = mysql_query("SELECT * FROM floats WHERE float LIKE'$float.%%%%%%%' AND float2 LIKE'$float2.%%%%%%%'");
$array = array();
while ($r = mysql_fetch_array($requst)) {
    // Lets store an array of differences between the provided float
    // and db floats, indexed by db float value
    $array[$r['float']] = abs($r['float'] - $float);
}
// Now lets sort the array by values(differences)
// keeping the keys intact
asort($array);
// The first key of the resulting array is the closest float to the provided float
$closest = array_pop(array_keys($array));
于 2012-07-19T14:44:26.743 回答