简体   繁体   中英

How to set min(value) variable as 0 when no value is returned by the sql query

$sql = "SELECT min(id) as sid FROM table1 where ....";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$sid = $row['sid'];

How can i set $sid as 0, when no value is returned by the sql query

(Here id in the table1 is int type)

Please help me....

If there are no matching rows, the min() function will return a NULL value, so use coalesce or ifnull() to turn it into a zero:

SELECT coalesce(min(id), 0) AS sid ...
SELECT ifnull(min(id), 0) AS sid ...

Try this:

$num_rows = mysql_num_rows($result);
if($num_rows == 0)
{
 $sid = 0;
}

mysql_num_rows return the number of rows for a query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM