简体   繁体   English

PHP准备语句 - 重置行指针

[英]PHP prepared statement - reset row pointer

I have the below code, which the comments should clearly explain. 我有下面的代码,评论应该清楚地解释。 I want to query a file for given information, and then once the results are returned, add a field onto the resulting array. 我想查询文件以获取给定的信息,然后在返回结果后,在结果数组中添加一个字段。 Then, access the resulting array later in my program. 然后,在我的程序中稍后访问生成的数组。

The problem with the code below is, i think the array is at the last record the second time i attempt to loop... and reset($stmt1) fails because $stmt1 is "not an array object"... 以下代码的问题是,我认为数组是第二次尝试循环时的最后一条记录...并且重置($ 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>";

?>

I don't think that's possible. 我不认为这是可能的。 But there's not really a compelling reason to try to do it that way anyway. 但无论如何,尝试这样做并不是一个令人信服的理由。

Keep it simple. 把事情简单化。 Just build an array the first time through. 只是第一次构建一个数组。

$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>";

This will, at worst, temporarily double your memory usage while the array is being built. 在最坏的情况下,这将在构建阵列时暂时加倍内存使用量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM