开发者

Grab min value in PHP from MySQL Database?

开发者 https://www.devze.com 2023-02-22 14:18 出处:网络
So I have some numbers that take the name \"id\" in my MySQL database. I tried this code: while($row = mysql_fetch_array($result))

So I have some numbers that take the name "id" in my MySQL database. I tried this code:

while($row = mysql_fetch_array($result))     
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo min($id);
} 

On the last line I tried to echo the min value for id, but it didn't work. Any suggestions?

ANSWER: Use "ASC LIMIT 1"

    while($row = mysql_fetch_assoc($sql)){    
$id=$row['id'];     
$user = $row['usrname'];     
$fname = $row['fname'];     
$lname = $row['lname'];
echo "<strong>User:</str开发者_JS百科ong> ".$user." ".$fname." ".$lname."<br/>";     
echo $id; 
}


$sql = mysql_query("SELECT * FROM users ORDER BY id ASC LIMIT 1");

while($row = mysql_fetch_assoc($sql))     
{
    $id=$row['id'];
    $user = $row['usrname'];
    $fname = $row['fname'];
    $lname = $row['lname'];

    echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
    echo $id;
} 


Try this:

$sql = 'SELECT min(id) as min FROM users';
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$min_id = $row['min'];


In case you cannot change the query order (sort by names?), you can determine the lowest $id by using a helper variable:

 $min = isset($min) ? min($min, $id) : $id;

And then print $min; after your loop.


If not able to use MIN() in MySQL, try this...

$smallestId = -PHP_INT_MAX;

while($row = mysql_fetch_assoc($sql)) {
   ...
   $smallestId = min($smallestId, $id);
}

If you never have any negative ids (you shouldn't), you could just change -PHP_INT_MAX to 0.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号