这是从mysql获取单个值的有效查询吗?


Is this a valid query for getting a single value from mysql?

$value = mysql_result(mysql_query("SELECT the_field 
                                     FROM the_table 
                                    WHERE other_field = 'whatever'"), 0); 

这是有效的,但我不知道这样做是否"合适"。是草率的编码吗?如果是这样,是否有更好的方法来获得一个单一的值?

我称之为懒惰编码——你没有检查错误。如果SQL中有错误或数据库关闭,这可能会导致令人困惑的错误消息。显式检查错误并给出有用的错误消息比让程序爆炸要好。

$result = mysql_query("SELECT the_field 
                       FROM the_table 
                       WHERE other_field = 'whatever'")
if (!result) {
    trigger_error(mysql_error($result));
}

更棒

$value = mysql_result(mysql_query("SELECT the_field 
                                     FROM the_table 
                                    WHERE other_field = 'whatever' LIMIT 1"), 0); 

我看不出这有什么不妥。此外,如果您只希望返回一行,您可以在末尾添加LIMIT 1