开发者

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

开发者 https://www.devze.com 2023-04-11 19:43 出处:网络
$value = mysql_result(mysql_query(\"SELECT the_field FROM the_table WHERE other_field = \'whatever\'\"), 0);
$value = mysql_result(mysql_query("SELECT the_field 
                                     FROM the_table 
                                    WHERE other_field = 'whatever'"), 0); 

This works, but I just don't know if it's "proper" to do it this way. Is it sloppy coding? If so, is there a better way to get one single value?开发者_开发百科


I'd call that lazy coding - you aren't checking for errors. This can lead to confusing error messages either if there's an error in your SQL or if the database is down. It's better to explicitly check for errors and giving a useful error message than to just let your program explode.

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


even better

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


I see nothing wrong with this. Additionally, if you want only one row back you can add LIMIT 1 at the end.

0

精彩评论

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