Jose
Jose

Reputation: 310

PHP foreach not working when iterating query result

Array to string conversion is thrown when I try to get a specific id and don't let me save the form. i just need the id of 'intervaloHorario' in order to autofill a field,but i don't know what am i doing wrong. Please give me a hand.

Error

Severity: 4096

Message: Object of class stdClass could not be converted to string

Model function

    public function get_idintervalo($idCitas) {

            $query = $this->db->query('SELECT intervaloshorarios.idIntervaloHorario FROM intervaloshorarios INNER JOIN citas '
                    . 'ON intervaloshorarios.idIntervaloHorario = citas.idIntervaloHorario '
                    . 'WHERE citas.idCitas = ' . $idCitas . ';');

            return $query->result();
}

Controller

$query = $this->Intervalos_Model->get_idintervalo($idCitas);


        if ($crud->getState() == "add") {
//It's wroking fine getting this
            $crud->change_field_type('idCitas', 'hidden', $idCitas);

foreach ($query as $key) {
            //Is not working fine (throws array to string conversion)
            $crud->change_field_type('idIntervaloHorario', 'hidden', $key);
        }

Upvotes: 0

Views: 122

Answers (2)

Todor Simeonov
Todor Simeonov

Reputation: 806

Is this OpenCart? If so use:

return $query->rows;

to get an array of returned rows.

Upvotes: 0

simurgrai
simurgrai

Reputation: 36

Assuming you are using CodeIgnitor Framework. You should write

foreach ($query as $key) {
    //Is not working fine (throws array to string conversion)
    $crud->change_field_type('idIntervaloHorario', 'hidden', $key->idIntervaloHorario);
}

because $query stores the query resultset in objects and $key is an object here. For more see manual https://www.codeigniter.com/userguide2/database/results.html

Upvotes: 1

Related Questions