我正在使用单例设计模式连接数据库。在下面我在我的数据库上运行查询,我想从这个查询中获取数据:
$db = Db::connect();
$query = $db->query("SELECT * FROM myTable");
while ($row = ???) {
// echo 'myTable' fields here. like = echo $row['someField']
}
我的Db课程:
class Db
{
private $connection;
private static $instance;
private function __construct()
{
$host = "localhost";
$user = "root";
$pass = "";
$name = "dictionary";
$this->connection = new mysqli($host, $user, $pass, $name);
}
public static function connect()
{
if (self::$instance == null) {
self::$instance = new Db();
}
return self::$instance;
}
public function query($sql)
{
$result = $this->connection->query($sql);
$records = array();
while ($row = $result->fetch_assoc()) {
$records[] = $row;
}
return $records;
}
}
我应该在代码中编写什么而不是???
?
答案 0 :(得分:0)
替换
while ($row = ???) {
// echo 'myTable' fields here. like = echo $row['someField']
}
带
foreach($query as $row)
echo $row['someField'];
注意:例如,您可能希望将$query
重命名为$rows
,因为这是一个更合适的名称。
答案 1 :(得分:0)
在while
循环的每次迭代中,使用array_shift()
函数从结果集中获取当前行,如下所示:
while ($row = array_shift($query)) {
echo $row['someField'] . "<br />";
}
以下是参考资料:
答案 2 :(得分:0)
您对Database类的->query()
方法的调用将返回结果行数组。因此,您需要做的就是像任何其他
$db = Db::connect();
$rows = $db->query("SELECT * FROM myTable");
foreach ($rows as $row ) {
echo $row['someField'];
}