mySQL / PHP:一行中的SQL语句,查询和结果分配?

时间:2012-07-19 14:58:43

标签: php mysql

是否可以在一行(或简称为更短)中重写下面的代码,甚至是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;

我见过很棒的,极其简化的结构,比如三元运算符(herehere - 顺便看到更多减少行的注释)将4-5行放在一个中,所以也许有些东西对于像上面这样的单个结果SQL查询。

1 个答案:

答案 0 :(得分: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;