PHP准备语句 - 重置行指针

时间:2011-04-19 21:33:02

标签: php sql arrays db2 reset

我有以下代码,评论应该清楚解释。我想查询文件以获取给定的信息,然后在返回结果后,在结果数组中添加一个字段。然后,在我的程序中稍后访问生成的数组。

以下代码的问题是,我认为数组是第二次尝试循环时的最后一条记录...并且重置($ stmt1)失败,因为$ stmt1“不是数组对象”...

<?php 

$sql1 = "SELECT dpdpt, SUM(dpbir) FROM dwhlib.dwdptstr WHERE dpdpt < '312' GROUP BY dpdpt ";

//Setup connection
$conn_resource = db2_connect ( "*LOCAL", "", "" );

//Verify connection successful
if (! $conn_resource) {
    echo "Connection failed. SQL Err:";
    echo db2_conn_error ();
    echo "<br/>";
    echo db2_conn_errormsg ();
    exit ();
}

//Prepare the stmt
$stmt1 = db2_prepare ( $conn_resource, $sql1 );

//Execute the prepared statement
if (! db2_execute ( $stmt1 )) {
    echo 'The db2 execute failed. ';
    echo 'SQLSTATE value: ' . db2_stmt_error ();
    echo ' Message: ' . db2_stmt_errormsg ();
    exit ();
}

//Loop through all rows, adding a third field
while ( $row1 = &db2_fetch_array ( $stmt1 ) ) {
    $row1[2] = "TEST";
}

//Reset stmt or array back to first record
//??

//Print results
echo "<table border=1>";
while ( $row = db2_fetch_array ( $stmt1 ) ) {
    echo "<tr>";
    echo "  <td>" . $row[0] . "</td>";
    echo "  <td>" . $row[1] . "</td>";
    echo "  <td>" . $row[2] . "</td>";
    echo "</tr>";
}
echo "</table>";

?>

1 个答案:

答案 0 :(得分:2)

我认为这不可行。但无论如何,尝试这样做并不是一个令人信服的理由。

保持简单。只是第一次构建一个数组。

$rows = array();
//Loop through all rows, adding a third field
while ( $row = db2_fetch_array ( $stmt1 ) ) {
    $row[2] = "TEST";
    $rows[] = $row;
}
db2_free_result($stmt1);

//Print results
echo "<table border=1>";
foreach($rows as $row) {
    echo "<tr>";
    echo "  <td>" . $row[0] . "</td>";
    echo "  <td>" . $row[1] . "</td>";
    echo "  <td>" . $row[2] . "</td>";
    echo "</tr>";
}
echo "</table>";

在最坏的情况下,这将在构建阵列时暂时加倍内存使用量。