我正在构建一个用于项目的自定义数据库类。我已经构建了一个fetchAssoc()方法,但是当我在while循环中调用它时,它不会移动到下一个记录。它反复调用第一条记录,直到脚本超时
以下是相关代码:
方法:
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);
}
}
脚本:
//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 />";
}
这是因为每次调用fetchAssoc函数时都会执行查询(至少我认为setResult在查看代码时应该这样做)。重置查询后,您将返回结果中的第一个关联,该关联将生成一个数组。因为它不断产生结果集的第一个关联,所以代码一直循环,直到达到max_execution时间。
如果我理解您的代码是正确的,那么fetchAssoc应该什么都不做,然后为这个->结果返回mysql_fetch_assoc。
我将为您分解:
//first lines of fetchAssoc
if($q == NULL)
{
$q = $this->query;
}
在使用此函数的代码段中,您不传递$q,因此$q始终是$this->查询。
$this->setResult($q);
然后调用setResult,它根据您自己的注释执行查询并设置这个->结果。因此,如果调用fetchAssoc函数,每次都会执行$this->查询,并且每次都会用该查询的结果刷新结果。
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->结果的第一行。这总是同一行,因为每次调用都会刷新查询和结果。