2012-01-06 93 views
0

我正在構建自定義數據庫類以供我的項目使用。我已經構建了一個fetchAssoc()方法,但是當我在while循環內調用它時,它不會移動到下一個記錄。它一次又一次地調用第一條記錄,直到腳本超時。
下面是相關代碼:PHP MYSQL數據庫類 - 獲取mysql_fetch_assoc方法移至下一條記錄

方法:

function runQuery($q) 
{ 
    $this->numQueries++; 
    $this->query = ($q); 
    $this->setResult($q); 
    $this->result; 
} 

function fetchAssoc($q = NULL) 
{ 
    if($q == NULL) 
    { 
     $q = $this->query; 
    } 
    $this->setResult($q); 
    if($q == NULL || mysql_num_rows($this->result) < 1) 
    { 
     return NULL;  
    } 
    else 
    { 
     return mysql_fetch_assoc($this->result); 
    } 
} 
    function setResult($q = NULL) 
{ 
    if($q == NULL) 
    { 
     $q = $this->query; 
    } 
    if($q == NULL) 
    { 
     return FALSE; 
    } 
    else 
    { 
     $this->result = @mysql_query($q); 
    } 
} 

SCRIPT:

//runQuery -- Should run the query and store the Result and Query 
$q = "SELECT * FROM make ORDER BY make"; 
$db->runQuery($q); 

//fetchAssoc -- return current row of result set and move pointer ahead 
foreach($db->fetchAssoc() as $key => $value) 
{ 
echo $value." has a foreign key of: ".$key."<br />";  
} 
//Also tried 
while($row = fetchAssoc()) 
{ 
    echo $value." has a foreign key of: ".$key."<br />";  
} 
+0

我也嘗試過:while($ row = fetchAssoc()),但它一遍又一遍地返回相同的結果 – Stewie 2012-01-06 16:12:02

+0

你可以發佈'setResult'方法嗎? – 2012-01-06 16:14:52

+0

功能的setResult($ Q = NULL) \t { \t \t如果($ Q == NULL) \t \t { \t \t \t $ Q = $這個 - >查詢; \t \t } \t \t 如果\t($ Q == NULL) \t \t { \t \t \t返回FALSE; \t \t } \t \t 其他\t \t {\t \t \t \t $這 - >結果= @mysql_query($ Q); \t \t \t} \t} – Stewie 2012-01-06 16:15:37

回答

2

那是因爲你執行查詢每次調用fetchAssoc功能(時間至少那是什麼我認爲setResult在查看你的代碼時應該是這樣做的)。查詢重置後,您將返回結果中的第一個關聯,從而生成一個數組。因爲它會導致結果集的第一次關聯,所以代碼將保持循環,直到達到max_execution時間。

fetchAssoc應該什麼也沒做,然後返回mysql_fetch_assoc這個 - >結果,如果我理解你的代碼是正確的。使用此功能,你沒有傳遞$ Q $等等q是總是這個 - $>查詢

//first lines of fetchAssoc 
if($q == NULL) 
{ 
    $q = $this->query; 
} 
在一段代碼

我將其分解爲您服務。

$this->setResult($q); 

然後,您可以調用setResult,根據您自己的註釋執行查詢並設置this-> result。因此,如果您調用fetchAssoc函數,則每次都會執行$ this-> query,並且每次都會用該查詢的結果刷新結果。

if($q == NULL || mysql_num_rows($this->result) < 1) 
{ 
    return NULL;  
} 
else 
{ 
    return mysql_fetch_assoc($this->result); 
} 

由於$ Q不能爲null這裏唯一的支票是NUM_ROWS(你在這種情況下,早期給了一個值的話)。只要出現這種情況,您就可以使用fetch_assoc返回$ this-> result的第一行。自從刷新查詢和每次調用的結果後,這總是相同的行。

+0

我不認爲查詢實際執行時,分配給一個變量。我以爲你必須有一個「或die()」或調用if(!$ result)才能真正執行查詢。 – Stewie 2012-01-06 16:21:08

+0

不允許查詢的函數調用是查詢執行的觸發器。你提到的兩件事情是構建一個如果執行查詢沒有按計劃進行就做些什麼的事情。 – hoppa 2012-01-06 16:21:58

+0

你是對的。我拿出$ this-> setResult($ q),它工作正常。謝謝。 – Stewie 2012-01-06 16:25:26

相關問題