2012-01-06 52 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

相关问题