我是php语言的新手。我只是从另一个示例项目复制数据库连接函数。代码如下。
public function getRows($conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$this->table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->db->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
有人能告诉我如何使用这个函数吗?我想使用WHERE,LIMIT,GROUP_BY和SELECT子句。当我输入这样的数组时,我收到错误消息"为foreach()"
提供的参数无效$conditions = array('where' => "user_name = '$username'");
$data = $userMo -> getRows($conditions);
答案 0 :(得分:3)
你犯了一个错误,正如其所说Invalid argument supplied for foreach()
这意味着它没有得到一个数组,并认为是否有多个WHERE呢?
所以试试这个
$conditions = array('where' => array('user_name' => $username));