Rutger Huijsmans Rutger Huijsmans - 2 months ago 6
PHP Question

Extracting value from Posted JSON

I'm trying to query using PHP.

I just expect the value to return to be a number but it's giving me back more:

$numberCount = $this->db->query("SELECT count(*) FROM users WHERE number = $number;");
$numberCountResult = $numberCount->result();
$this->set_response($numberCountResult, REST_Controller::HTTP_CREATED);


My API will now return me:

[
{
"count(*)": "1"
}
]


I just want it to give me:

[
{
"1"
}
]


How can I just extract that single value?

Answer

Description To achieve this first use aliasing in your raw query as describe in the following code snippet and also make use of row() function for finding the query result.

Code

    $numberCount = $this->db->query("SELECT count(*) as number FROM users WHERE number = $number;");
    $row = $numberCount->row();

    if (isset($row)) {
        $numberCountResult = $row->numer;
    }
    $this->set_response($numberCountResult, REST_Controller::HTTP_CREATED);
Comments