php - Codeigniter Query Builder - Need to check if entry exists in multiple columns

65

We have a table with multiple attributes, such as:

TABLE_ATTRIBUTES
ID,   Color, Size, Weight
111, Red,   XL     null
112, null,    SM    10

I want to build a method inside my model, that returns the row ID, by checking all the columns for any attributes. For example, if I want to pass 'green', 'SM', '9'.

What's the best way to build this Codeigniter DB Query?

I have something like this, but it's not working:

$this->db->select('id');
->or_where($color === NULL ? 'color IS NOT NULL' : 'color =', $color)
->or_where($size === NULL ? 'size IS NOT NULL' : 'size =', $size)
->or_where($weight === NULL ? 'weight IS NOT NULL' : 'weight =', $weight_10)
$row = $this->db->get('product')->row();
317

Answer

Solution:

Your firstor_where should just bewhere according to the documentation so you probably want to alter it slightly:

$this->db->select('id');
->where($color === NULL ? 'color IS NOT NULL' : 'color =', $color)
->or_where($size === NULL ? 'size IS NOT NULL' : 'size =', $size)
->or_where($weight === NULL ? 'weight IS NOT NULL' : 'weight =', $weight_10)
$row = $this->db->get('product')->row();

See this doc about$this->db->or_where() for their example: https://www.codeigniter.com/userguide3/database/query_builder.html

People are also looking for solutions to the problem: php - Regex for starting with and not ends

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.