0

I am writing a custom function in a Member controller. The purpose of the function is this:-

  1. First it checks if an id exists in the members table.
  2. If it doesn't exist then it returns 0;
  3. if it exists, then it checks whether the isActive status is 0 or 1;
  4. if it's 0, then it returns 0, else 1;

Now, I am writing the function as these:-

public function memberExist($id)
{
    $query = "SELECT Member.id FROM members AS Member WHERE Member.id = $id AND Member.isActive = 1";
    // Here I want to write something like:
    // if($this->query($query)->num_rows()>0) return 1; else return 0;
}

However, the problem is, I don't now how to get number of rows from query builder(sorry if the name is not exact, I am new to cakephp).

$this->query($query) returns array.

In controller, we can use following method to get number of rows,

$userdata = $this->Member->find('count',array('conditions'=>array('Member.id'=>$id, 'Member.isActive'=>1)));

But how to apply count procedure in the Model?

1
  • $this->Member is a model object, think about that. Commented Jul 7, 2016 at 17:28

2 Answers 2

1

if $this->query($query) return arrays, you can count row by :

$records = $this->query($query);
$n = count($records); //count of rows

read this for details http://www.w3schools.com/Php/func_array_count.asp

Sign up to request clarification or add additional context in comments.

Comments

0

This should work for multiple member ids (where 1, 2, 3 ... is your member ids):

$query = "SELECT COUNT(Member.id) as count FROM members AS Member WHERE Member.id in (1, 2, 3, 4) AND Member.isActive = 1;";

for single member id:

$query = "SELECT COUNT(Member.id) as count FROM members AS Member WHERE Member.id = ".$id." AND Member.isActive = 1;";

Number of rows will represented by $your_result_var['count'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.