Reputation: 33
I'm trying to list the indexes of an array, and it keeps throwing errors in my face.
I am getting this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: sender
Now for some code details: My print line:
<div class="left"><label>Afsender: </label><p><?=$reservation['sender'] . ' (' . $reservation['email'] . ')'?></p></div></pre>
My controller: (using phil sturgeon's template library for CodeIgniter)
public function readReservation($id)
{
$data['reservation'] = $this->reservation_model->getReservation($id);
$this->template->build('admin/readReservation_view', $data);
}
My Model:
public function getReservation($id)
{
$query = $this->db->where('id', $id)->get('ita_reservations');
if ($query->num_rows > 0)
{
return $query->result();
}
else
return false;
}
My sql:
CREATE TABLE IF NOT EXISTS `ita_reservations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sender` varchar(200) NOT NULL,
`email` varchar(200) NOT NULL,
`date` varchar(200) NOT NULL,
`time` varchar(200) NOT NULL,
`persons` varchar(200) NOT NULL,
`phone` varchar(200) NOT NULL,
`message` varchar(1000) NOT NULL,
`time_received` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`confirmed` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
Now what baffles me, is that the same code works elsewhere, but with a different variable name. To increase my confusion, this is the var_dump
from the line above my print:
array(1) { [0]=> object(stdClass)#42 (10) { ["id"]=> string(1) "1" ["sender"]=> string(7) "Kenneth" ["email"]=> string(17) "[email protected]" ["date"]=> string(10) "23/05/2013" ["time"]=> string(5) "18:00" ["persons"]=> string(1) "4" ["phone"]=> string(8) "30243681" ["message"]=> string(12) "Ja nemlig ja" ["time_received"]=> string(19) "0000-00-00 00:00:00" ["confirmed"]=> string(1) "0" } }
The sender index is clearly there, and the array is clearly loaded properly. (All indexes throw errors, not just sender).
What's going on, and what am I missing? Yes, I know I should check for isset
or empty
, but it exists, and the page cannot be loaded if the index doesn't exist so checks are kindof moot.
Upvotes: 1
Views: 938
Reputation: 43298
You have an object inside an array (see your var_dump
), so to get the reservation sender you have to use the following:
$reservation[0]->sender
Or better yet, instead of returning the whole result set from your function, you should only return one row (assuming id's are unique, your query will return only one row anyway):
public function getReservation($id)
{
$query = $this->db->where('id', $id)->get('ita_reservations');
if ($query->num_rows > 0)
{
return $query->row();
}
else
return false;
}
With this you can use:
$reservation->sender
Upvotes: 1