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);
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.
精彩评论