我正在构建一个自定义数据库类以供我的项目使用。我已经构建了一个 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->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 永远不会为空(在之前的情况下您给了它一个值),这里唯一的检查是在 num_rows 上。只要是这种情况,您就可以使用 fetch_assoc 返回 $this->result 的第一行。由于您每次调用都刷新查询和结果,因此这始终是同一行。
关于PHP MYSQL 数据库类 - 获取 mysql_fetch_assoc 方法移动到下一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8760776/