0
我是PDO的新手,我正在從MySQLi轉換到它,因爲我一直在使用我的網絡空間。FETCH_ASSOC PDO連續循環
我正在嘗試使用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);
}
}
}
您執行每取之前,所以你每次從頭開始。 –
@KIKOSoftware是否應該從類中移除執行調用,然後在我之前使用過的地方總是執行'...-> execute() - > fetchArray();' –
您只需執行一次查詢,然後就可以獲取所有行。我會在你的'prepareSQL()'方法中放入execute,然後調用'prepareAndExecuteSQL()'方法。 –