August 19, 2012

Why is count(id) resulting 3 dimensional array?

Question by goose

Im using this direct query method in cakephp to get a count (against the norms of MVC).

$count = $this->History->query("SELECT count(id) AS x FROM ratings WHERE id='3' AND employee='28'");

But it turns out that, i need to use $count[0][0]['x'] to get the value.

Why isnt it available at $count['x']?

Answer by Starx

Simply, its because the function

$this->History->query(....);

does not return a single dimensional array. I will suggest you to create a helper function, which extracts the single dimensional array and return it.

function single_query($query) {
    $result = $this->History->query($query);
    return $result[0][0];
}

then use it

$count = $this->single_query("SELECT count(id) AS x FROM ratings WHERE id='3' AND employee='28'");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!