note 109186 added to mysqli-result.fetch-object

From: Date: Tue, 26 Jun 2012 17:18:48 +0000
Subject: note 109186 added to mysqli-result.fetch-object
Groups: php.notes 
Request: Send a blank email to php-notes+get-188872@lists.php.net to get a copy of this message
As indicated in the user comments of the mysql_fetch_object, it is important to realize that class fields get values assigned to them BEFORE the constructor is called. For example; <?php class Employee { private $id; public function __construct($id = 0) { $this->id = $id; } } // some code for creating a database connection... i.e. mysqli object .... $result = $con->query("select id, name from employees"); $anEmployee = $result->fetch_object("Employee"); ?> will result in the ID being 0 because it is overridden by the constructor. Therefore, it is useful to check if the class field is already set. I.e. <?php class Employee { private $id; public function __construct($id = 0) { if (!$this->id) { $this->id = $id } } } ?> Also note that the fields which will be assigned by fetch_object are case sensitive. If your table has the field "ID", it will result in the class field $ID being set. A simple work-around is to use aliases. I.e. "SELECT *, ID as id FROM myTable" I hope this helps some people. ---- Server IP: 69.147.83.197 Probable Submitter: 84.27.22.155 ---- Manual Page -- http://www.php.net/manual/en/mysqli-result.fetch-object.php Edit -- https://master.php.net/note/edit/109186 Del: integrated -- https://master.php.net/note/delete/109186/integrated Del: useless -- https://master.php.net/note/delete/109186/useless Del: bad code -- https://master.php.net/note/delete/109186/bad+code Del: spam -- https://master.php.net/note/delete/109186/spam Del: non-english -- https://master.php.net/note/delete/109186/non-english Del: in docs -- https://master.php.net/note/delete/109186/in+docs Del: other reasons-- https://master.php.net/note/delete/109186 Reject -- https://master.php.net/note/reject/109186 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188872) next »