How do I add a where clause in the following query using the CI? E.g. WHERE name = 'Joe'
<?php
include 'dbclass.php';
$db = new DB();
$users = $db->getRows('users',array('order_by'=>'id DESC'));
if(!empty($users)):
$count = 0;
foreach($users as $user):
$count ;
?>
dbclass.php snippet:
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$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'];
}
$result = $this->db->query($sql);
I want help in passing the Where clause condition. I am using Codeignitor 4.
CodePudding user response:
Not sure where the codeigniter parts are in this, that looks like code you have written, so just add a where
key to the array you are passing like this
$users = $db->getRows('users',array('where' => ["name => 'Joe']",
'order_by'=>'id DESC'));