#1 redguan
find 返回一条数组。应该是这样的格式
array(
'uid'=>1
'username'=>'admin'
);
而非:
array(
0=>array('uid'=>1,'username'=>'admin')
);
findAll 是返回一个多维数组。
根的KEY 应该是主键而非自动加1的数字
SPMODEL.PHP 修改
array(
1=>array('uid'=>1,'username'=>'admin');
4=>array('uid'=>4,'username'=>'demo');
);
/**
*返回的数组转换成以主键作为数组索引
*
*
**/
protected function changePk($arr){
foreach($arr as $data)$arr2[$data[$this->pk]] = $data;
return $arr2;
}
/*
*
*返回的数组转换成单条数组形式
*
*/
protected function changeOne($arr){
foreach ($arr[0] as $k =>$d) $arr2[$k]=$d;
return $arr2;
}
protected function make_find_sql($conditions = null, $sort = null, $fields = null, $limit = null){
$where = "";
$fields = empty($fields) ? "*" : $fields;
if(is_array($conditions)){
$join = array();
foreach( $conditions as $key => $condition ){
$condition = $this->__val_escape($condition);
$join[] = "{$key} = '{$condition}'";
}
$where = "WHERE ".join(" AND ",$join);
}else{
if(null != $conditions)$where = "WHERE ".$conditions;
}
if(null != $sort)$sort = "ORDER BY {$sort}";
if(null != $limit)$limit = "LIMIT {$limit}";
$sql = "SELECT {$this->tbl_name}.{$fields} FROM {$this->tbl_name} {$where} {$sort} {$limit}";
return $this->_db->getArray($sql);
}
/**
* 从数据表中查找一条记录
*
* @param conditions 查找条件,数组array("字段名"=>"查找值")或字符串,
* 请注意在使用字符串时将需要开发者自行使用__val_escape来对输入值进行过滤
* @param sort 排序,等同于“ORDER BY ”
* @param fields 返回的字段范围,默认为返回全部字段的值
*/
public function find($conditions = null, $sort = null, $fields = null)
{
return $this->changeOne($this->make_find_sql($conditions, $sort, $fields, 1));
/*
if( $record = $this->findAll($conditions, $sort, $fields, 1) ){
return array_pop($record);
}else{
return FALSE;
}
*/
}
/**
* 从数据表中查找记录
*
* @param conditions 查找条件,数组array("字段名"=>"查找值")或字符串,
* 请注意在使用字符串时将需要开发者自行使用__val_escape来对输入值进行过滤
* @param sort 排序,等同于“ORDER BY ”
* @param fields 返回的字段范围,默认为返回全部字段的值
* @param limit 返回的结果数量限制,等同于“LIMIT ”,如$limit = " 3, 5",即是从第3条记录开始获取,共获取5条记录
*/
public function findAll($conditions = null, $sort = null, $fields = null, $limit = null)
{
return $this->changePk($this->make_find_sql($conditions, $sort, $fields, $limit));
}
/**
* 过滤转义字符
*
* @param value 需要进行过滤的值
*/
public function __val_escape($value)
{
return $this->_db->__val_escape($value);
}
仅供参考
2010-05-26 16:05:20