Fahad Sultan
Fahad Sultan

Reputation: 9

CodeIgniter active record query not returning results

In my CodeIgniter2 model, I am using a like() query to fetch all the products having first name rice which is not working controller.

If I use get_where('name') instead of like(), it works fine.

public function fetchdeal_products($id) {
    $this->db->select('*');
    $this->db->from('products');
    $q = $this->db->like("name", $id);
    
    if ($q->num_rows() > 0) {
        foreach (($q->result()) as $row) {
            $data[] = $row;
        }
        return $data;
    }    
}

Upvotes: 1

Views: 657

Answers (5)

Abdulla Nilam
Abdulla Nilam

Reputation: 38652

public function fetchdeal_products($id) 
{
    $query = $this->db->query("Select products.* From products Where (products.name Like '%$id%')");
    $result = $query->result_array();
    return $result;
}

EDIT 01 (2024/08/21)

public function fetchdeal_products($id)
{

    $this->db->like('name', $id);
    $query = $this->db->get('products'); 
    
    return $query->result_array();
}

Upvotes: 0

mickmackusa
mickmackusa

Reputation: 48031

The missing part is ->get() to actually execute the query. When you were using get_where() that is a hybridized method what both declares the WHERE clause AND executes the query. like() does not execute the query, so get() is necessary after building the whole query.

Your whole model method can be boiled down to the following:

public function fetchdeal_products(string $id): array
{
    return $this->db->like('name', $id)->get('products')->result();
}
  • chain your methods together for maximum elegance
  • ->select('*') is implied and can be safely omitted
  • the table declaration can be move from ->from('products') to ->get('products')
  • $q->num_rows() > 0 is an unneeded check; if there are no results, return an empty array
  • the loop serves no purpose, just return the result() (an array of objects)

Upvotes: 0

shankar kumar
shankar kumar

Reputation: 648

you have to write it as bellow.

public function fetchdeal_products($id) {
    $this->db->like("name", $id);

    $q = $this->db->get('products');
    if ($q->num_rows() > 0) {
        foreach (($q->result()) as $row) {
            $data[] = $row;
        }

        return $data;
    }    
}

Upvotes: 0

Eustace
Eustace

Reputation: 333

You are using $this->db_like() incorrectly.

$this->db->like('title', 'match'); 
// Produces: WHERE title LIKE '%match%'

(from documentation)

In your case the usage would be

$this->db->like('name', 'rice')

More info

Upvotes: 0

Craig
Craig

Reputation: 1823

The database LIKE function only creates a LIKE in the SQL statement. You'll still need to call the GET mothod afterwards; Like this;

$this->db->like('name', $id);
$q = $this->db->get();

Upvotes: 1

Related Questions