请帮看下代码是否可以改进

#1 manjinzi

public function getdata($lang = null) {
        $conditions = array();
        if ($lang) {
            $conditions['lang'] = $lang;
        }
        return $this->spCache(3600 * 24)->findAll($conditions, 'px DESC', null, null);
    }

带个参数 没有问题,不带参数就会出错多了一个where,能不能改进下,我现在是这么做的,判断下$conditions 是否为空

        if ($conditions) {
            return $this->spCache(3600 * 24)->findAll($conditions, 'px DESC', null, null);
        } else {
            return $this->spCache(3600 * 24)->findAll(null, 'id DESC', null, null);
        }
SELECT * FROM cp_lang WHERE ORDER BY px DESC
执行错误: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY px DESC' at line 1

2011-04-06 10:55:57

#2 manjinzi

public function findAll($conditions = null, $sort = null, $fields = null, $limit = null) {
        $where = "";
        $fields = empty($fields) ? "*" : $fields;
        if (is_array($conditions) && count($conditions)>0) {
            $join = array();
            foreach ($conditions as $key => $condition) {
                $condition = $this->escape($condition);
                $join[] = "{$key} = {$condition}";
            }
            $where = "WHERE " . join(" AND ", $join);
        } else {
            if (null != $conditions
                )$where = "WHERE " . $conditions;
        }

红色 是我加上去的,可以使用

2011-04-06 11:03:07

#3 jake

先定义,再使用,判断空值,这几步都是比较严谨的写法。

2011-04-06 12:10:41