How to write codeigniter as a request

The problem is that it displays all lines from db instead of displaying only those lines that contain keywords to search. Please help me.

public function search($data) { $name = $data["name"]; $surname = $data["surname"]; $this->db->select('*'); $this->db->from('workers'); $this->db->like('name', '%' . $name . '%'); $this->db->or_like('surname', '%' . $surname . '%'); $query = $this->db->get(); 
+6
source share
2 answers

You wrote CI as an invalid request. See the documentation on how to write it down correctly.

Your request should be like this. No need to add % . CI add them if you do not pass the third parameter of a similar function.

 $this->db->select('*'); $this->db->from('workers'); $this->db->like('name', $name); $this->db->or_like('surname', $surname); $query = $this->db->get(); 

Better do with some valid data like this.

 $this->db->select('*'); $this->db->from('workers'); if($name) { $this->db->or_like('name', $name); } if($surname) { $this->db->or_like('surname', $surname); } $query = $this->db->get(); 
+3
source

Shaiful is correct, your statements like this are spelled incorrectly, but I would like to dwell on this so that you are careful with the or_ in the Active Record. In Codeigniter, they do not use parentheses, so the following is fine:

 $this->db->select('*'); $this->db->like('name', $name); $this->db->or_like('surname', $surname); $query = $this->db->get('workers'); 

He produces:

 SELECT * FROM `workers` WHERE `name` LIKE `%$name%` OR `surname` LIKE `%$surname%`; 

But if you extend the request later, the following will not work correctly:

 $this->db->select('*'); $this->db->where('id', $id); $this->db->like('name', $name); $this->db->or_like('surname', $surname); $query = $this->db->get('workers'); 

This gives:

 SELECT * FROM `workers` WHERE `id`=`$id` AND `name` LIKE `%$name%` OR `surname` LIKE `%$surname%`; 

The problem with the second example is that the WHERE becomes optional due to OR later in SQL.

Codeigniter 3 led to the possibility of using parentheses, and I would recommend the following approach if it is likely that your request will become more complex later.

Thus, a safer approach, in my opinion, when using the or_ :

 $query = $this->db->select('*')->from('workers') ->group_start() ->like('name', $name) ->or_like('surname', $surname) ->group_end() ->get(); 

In your current example, however, there is no problem with what Shaiful gave, and it is fully compatible with Codeigniter 2.

0
source

Source: https://habr.com/ru/post/987596/


All Articles