class: mysqli_fetch_object
I followed the php.net's doc to get certain object's result from fetch_object
,
$mysqli = new mysqli("localhost", "root", "tklau", "xx_2011");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT cnt_id, cnt_email1
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
if ($result = $mysqli->query($query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
print_r($obj);
//echo $obj->cnt_email1;
}
/* free result set */
$result->close();
}
/* close connection */
$mysqli->close();
I will get this,
stdClass Object
(
[cnt_id] => 2
[cnt_email1] => rocco@xx.net
)
stdClass Object
(
[cnt_id] => 1
[cnt_email1] => lola@xx.co.uk
)
But I want to make this code into a class instead,
#connects the database and handling the result
class __database {
protected $connection = null;
protected $error = null;
#make a connection
public function __construct($hostname,$username,$password,$database)
{
$this -> connection = new mysqli($hostname,$username,$passwo开发者_开发知识库rd,$database);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
public function fetch_object($query)
{
$result = $this -> connection -> query($query);
if($result)
{
while ($row = $result->fetch_object()) {
return $row;
}
}
else
{
$this -> error = $this -> connection -> error;
return false;
}
}
#display error
public function get_error()
{
return $this -> error;
}
#closes the database connection when object is destroyed.
public function __destruct()
{
$this -> connection -> close();
}
}
so, I will call the class function like this,
$sql = "
SELECT cnt_id, cnt_email1
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
$items = $connection -> fetch_object($sql);
print_r($items);
but I get only one row from the result which is not correct,
stdClass Object
(
[cnt_id] => 2
[cnt_email1] => lau@xx.net
)
it must be something wrong in my class function of fetch_object
- how can I fix it? please advise...
You function is returning when it finds the first result.
return $row;
You should store each row in an array and then return the array.
if($result){
$function_result = array();
$i = 0;
while($row = $result->fetch_object()){
$function_result[$i] = $row;
$i++;
}
return $function_result;
}
精彩评论