我按照php.net的doc来从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();
我会得到这个,
stdClass Object
(
[cnt_id] => 2
[cnt_email1] => rocco@xx.net
)
stdClass Object
(
[cnt_id] => 1
[cnt_email1] => lola@xx.co.uk
)
但我想把这段代码变成一个类,
#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,$password,$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();
}
}
所以,我会像这样调用类函数,
$sql = "
SELECT cnt_id, cnt_email1
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
$items = $connection -> fetch_object($sql);
print_r($items);
但是我从结果中只得到一行不正确,
stdClass Object
(
[cnt_id] => 2
[cnt_email1] => lau@xx.net
)
我{class 1}}的班级功能一定是错的 - 我该如何解决?请指教......
答案 0 :(得分:2)
当您找到第一个结果时,您的功能正在返回
return $row;
您应该将每一行存储在一个数组中,然后返回该数组。
if($result){
$function_result = array();
$i = 0;
while($row = $result->fetch_object()){
$function_result[$i] = $row;
$i++;
}
return $function_result;
}