0

if (result > 0)是否可以仅用一行(或更短)重写下面的代码,甚至可以使用语句?

// a simple query that ALWAYS gets ONE table row as result
$query  = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id     = $result->id;

我已经看到了很棒的、极其简化的结构,例如三元运算符(这里这里-顺便说一下,看到更多简化行的评论)将 4-5 行合二为一,所以也许有一些像上面这样的单结果 SQL 查询。

4

1 回答 1

3

你可以缩短

$query  = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id     = $result->id;

$id = $this->db->query("SELECT id FROM mytable WHERE this = that")->fetch_object()->id;

但是,如果任何函数返回意外响应,原始代码将发出错误。最好写:

$query  = $this->db->query("SELECT id FROM mytable WHERE this = that");
if (!$query) {
     error_log('query() failed');
     return false;
}
$result = $query->fetch_object();
if (!$result) {
     error_log('fetch_object() failed');
     return false;
}
$id     = $result->id;
于 2012-07-19T15:04:27.657 回答