我是 PDO 的新手,由于最近在我的网络空间中遇到的问题,我正在从 MySQLi 转换到它。
我正在尝试使用 FETCH_ASSOC 循环遍历结果以获取查询生成的各个记录,但是,循环永无止境,并且一遍又一遍地不断重复结果中的第一条记录。有什么建议么?
<?php
$Request = databaseManager::getDB()->prepareSQL("SELECT Username, 2Wins, 2Loses, (2Wins/(2Wins+2Loses))*100 as WinRate FROM tblUsers ORDER BY 4 DESC");
//$LstResults = $Request->fetchAll();
while($LstResults = $Request->fetchArray()){
if($LstResults["WinRate"] >= 50){ ?>
<tr>
<td><?php echo $LstResults["Username"]; ?></td>
<td>
<div class="progress progress-xs">
<div class="progress-bar progress-bar-success" style="width: <?php echo $LstResults["WinRate"]; ?>%"></div>
</div>
</td>
<td><span class="badge bg-green"><?php echo intval($LstResults["WinRate"]); ?></span></td>
</tr>
<?php }
} ?>
班级
class databaseManager{
protected $dbHND;
protected $currentSQLStatement;
protected $bind;
private $StrDBHost='localhost';
private $StrDBPort = "3306";
private $StrDBUser='thomassm_sqlogin';
private $StrDBPass='password';
private $StrDBName='thomassm_CadetPortal';
public function __construct(){
if ($this->dbHND = new PDO ('mysql:host=' . $this->StrDBHost . ';dbname=' . $this->StrDBName . ';port=' . $this->StrDBPort, $this->StrDBUser, $this->StrDBPass)){
$this->bind = null;
}
else{
return false;
}
}
static public function getDB(){
$tmpInstance = new self ();
return $tmpInstance;
}
public function prepareSQL($sqlQueryString = null){
if ($sqlQueryString === null){
$this->currentSQLStatement === false;
return false;
}
elseif (is_array ( $sqlQueryString )){
if ($this->currentSQLStatement = $this->dbHND->prepare ( $sqlQueryString [0] )){
$this->bind = $sqlQueryString [1];
return $this;
}
else{
throw new \Exception ( "Could not prepare SQL Statement, " . print_r ( $this->dbHND->errorInfo () ) );
return false;
}
}
else{
if ($this->currentSQLStatement = $this->dbHND->prepare ( $sqlQueryString )){
return $this;
}
else{
throw new \Exception ( "Could not prepare SQL Statement, " . print_r ( $this->dbHND->errorInfo () ) );
return false;
}
}
}
public function fetchArray(){
if (! $this->currentSQLStatement){
return false;
}
elseif ($this->bind != null){
$this->currentSQLStatement->execute ( $this->bind );
return $this->currentSQLStatement->fetch ( PDO::FETCH_ASSOC );
}
else{
$this->currentSQLStatement->execute ();
return $this->currentSQLStatement->fetch ( PDO::FETCH_ASSOC );
}
}
public function fetchAll(){
if (! $this->currentSQLStatement){
return false;
}
elseif ($this->bind != null){
$this->currentSQLStatement->execute ( $this->bind );
return $this->currentSQLStatement->fetchAll ( PDO::FETCH_ASSOC );
}
else{
$this->currentSQLStatement->execute ();
return $this->currentSQLStatement->fetchAll ( PDO::FETCH_ASSOC );
}
}
}
正如 KIKO Software 在对问题的评论中所说,我只需要运行一次 execute 否则它将重置循环计数。我已经从 fetchArray 代码中删除了执行,现在在调用 fetchArray 之前调用它,如下所示:
public function fetchArray(){
if (! $this->currentSQLStatement){
return false;
}
else{
return $this->currentSQLStatement->fetch ( PDO::FETCH_ASSOC );
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句