MySQLi fetch_all连续调用错误

时间:2018-01-11 23:05:26

标签: php mysql mysqli

我已经设置了一个类来处理我的MySQLi调用。这些电话正在按预期工作,所以没有问题。

我最近将结果处理从我的类的查询方法中移除到两个单独的setter方法。现在有两个连续fetch_all次呼叫导致错误。

单个fetch_all调用的上一个(工作)代码会将结果加载到两个数组res_rowsres_cols中:

// Convert results into two sets of values
// and store in properties
// $res_rows=results by row (column names in element 0)
//           Each row is an indexed array 
// $res_cols=results by column (associative arrays)
//           Key is the column name; Value is an array

$results=$res->fetch_all(MYSQLI_ASSOC);

// $colNames is an array of the column names
$colNames=array_keys($results[0]);

// Rows
foreach($results as $r) {
    $this->res_rows[]=array_values($r);
}
array_unshift($this->res_rows,$colNames);

// Columns

$vals=array();

// Count the number columns in the query
$numCols=count($colNames);

// Iterate through the columns
for($i=0;$i<$numCols;$i++) {

    $col=$colNames[i];
    $storage=array();

    foreach($results as $r) {
        $storage[]=$r[$colNames[$i]];
    }

    $vals[]=$storage;
}

$this->res_cols=array_combine($colNames,$vals);

我已将此代码移动到两个方法setRes_rowssetRes_cols中并按顺序调用它们(请参阅代码)。每种方法都使用fetch all从结果对象中提取结果。

$this->setRes_rows($res);
$this->setRes_cols($res);

第一次调用的行为与预期的一致,第二次调用返回一个空数组。

如果我反转呼叫(例如,首先是setRes_cols),则会发生同样的事情(第一次呼叫按预期工作;第二次呼叫为空)。所以我知道代码很好。我甚至改变了其中一个方法中的所有变量名,但没有效果。

我在调用之间转储了结果对象上的所有属性和方法,但它看起来并没有改变。但由于某种原因,第二个fetch_all不起作用。

简单的解决方法是让我使用单个fetch_all然后调用我的方法。但是我很想知道我是否有什么奇怪的东西。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

看起来你需要在fetch_all之后重置结果指针 我没有在专门针对fetch_all的文档中找到任何内容 - 只是在fetch_assoc()之后重置,我们可以找到对data_seek()的引用:example

所以这就是你应该做的:

在第二个fetch_all()之前执行

$res->data_seek(0);  // where $res is your mysqli result Object

这基本上将结果指针设置为第一条记录。