我目前正在获取项目中有3个数据的教堂清单,但是问题是当我尝试循环while
时它会无限循环,而当var_dump
仅显示1个数据时。但是当我使用PDO
时,它可以正常工作。
这是我的数据库类
<?php
namespace classes\worker;
use \mysqli;
const DB_HOST = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = '';
const DB_NAME = 'db_sk';
class Database {
public function __construct() {
$this->db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($this->db->connect_error) {
die($this->db->connect_error);
}
}
protected function select($table, $condition = '', $column = '*') {
$condition = ($condition == '') ? '' : ' WHERE ' . $condtion;
$query = 'SELECT ' . $column . ' FROM ' . $table . $condition . ';';
$sth = $this->db
->query($query);
if($sth) {
return $sth;
} else {
return $this->db
->error;
}
}
protected function insert($table, array $data) {
ksort($data);
$column = join(', ', array_keys($data));
$values = '"' . join('", "', array_values($data)) . '"';
$query = 'INSERT INTO ' . $table . '(' . $column . ') VALUES(' . $values . ');';
$sth = $this->db
->query($query);
if($sth) {
return $this->db
->insert_id;
} else {
return $this->db
->error;
}
}
protected function update($table, array $data, $condition) {
ksort($data);
$set = '';
foreach($data as $keys => $values) {
$set .= $keys . '="' . $values . '", ';
}
$set = rtrim($set, ', ');
$query = 'UPDATE ' . $table . ' SET ' . $set . ' WHERE ' . $condition . ';';
$sth = $this->db
->query($query);
if($sth) { return true; } else { return false; }
}
protected function delete($table, $condition) {
$query = 'DELETE FROM ' . $table . ' WHERE ' . $condition . ';';
$sth = $this->db
->query($query);
if($sth) { return true; } else { return false; }
}
}
这是我的教堂课
<?php
namespace classes\helper;
use \classes\worker\{Database};
final class Church extends Database {
public function getChurch() : object {
return $this->select('tbl_church_info', '', 'acc_id, name');
}
}
这是我测试结果的页面:
<?php
use \classes\helper\{Church};
$church = (new Church())->getChurch();
var_dump($church); // only show 1 data but has 3 data in database
while(($row = $church->fetch_assoc()) !== NULL) {
echo $row['acc_id'];
} // which loop infinite
?>
答案 0 :(得分:1)
这是因为您仅调用一次fetch_assoc
$church = (new Church())->getChurch()->fetch_assoc();
var_dump($church); // only show 1 data but has 3 data in database
while(($row = $church)) {
echo $row['acc_id'];
} // which
可能在哪里
$church = new Church();
while($row = $church->getChurch()->fetch_assoc()) {
echo $row['acc_id'];
} // which
答案 1 :(得分:0)
我所做的解决方案就是这样。在教会类中,我已经返回了结果。
<?php
namespace classes\helper;
use \classes\worker\{Database};
final class Church extends Database {
public function getChurch() : array {
$selected = $this->select('tbl_church_info', '', 'acc_id, name');
while(($row = $selected->fetch_assoc()) !== NULL) {
$tmp[] = $row;
}
return $tmp;
}
}
然后我很容易看到结果的输出,
<?php
use \classes\helper\{Church};
$church = new Church();
foreach($church->getChurch as $list) {
var_dump($list); // and works properly :)
}
?>