AJ Birone AJ Birone - 4 months ago 14
PHP Question

How can a handle errors from db2_fetch_assoc in PHP?

I have a query to a program that I am running on my iSeries. I understand that sometimes this query will fill occasionally because there are no records to select. Every time the query fails, it logs to php.log as:

PHP Warning: db2_fetch_assoc(): Fetch Failure in /www/zendsvr6/htdocs/views/hp1110.php on line 82


I am looking for a solution to prevent this error from logging. I know that I can disable PHP error logging already. I do not want to disable the logging.

Here is a sample of the code:

$stmt = db2_prepare($conn, $sql);

if (!$stmt) {
$code = db2_stmt_error();
$msg = db2_stmt_errormsg();
// TODO in production do not display SQL. Log it instead.
die("Failed to prepare $sql. Reason: $code $msg");
} //(if (!$result))

$bound1 = db2_bind_param($stmt, 1, "item", DB2_PARAM_IN);
$bound2 = db2_bind_param($stmt, 2, "house", DB2_PARAM_IN);
$bound3 = db2_bind_param($stmt, 3, "counter", DB2_PARAM_INOUT);

if (!$bound1 || !$bound2 || !$bound3) {
die("Failed to bind one or more parameters.");
} //(if (!$bound1 || !$bound2 || !$bound3) )

// execute with bound parameters.
$result = db2_execute($stmt);

if (!$result) {
$code = db2_stmt_error();
$msg = db2_stmt_errormsg();
// TODO in production do not display SQL. Log it instead.
die("Failed to execute $sql. Reason: $code $msg");
} //(if (!$result))

if (!$counter) {
return array();//
} //(if (!$counter))

// success. create array to return to caller.
$rows = array();
while (($row = db2_fetch_assoc($stmt)) != false) {
$rows[] = $row;
} //(while...)

// this returns it to the caller.
return $rows;

} //(getParts)


Thanks!

Answer

If the db2 driver logs that every time you try to fetch from a result which has no(more) rows available, then you can avoid it by fetching only exactly the number of rows returned:

$total_rows = db2_num_rows($stmt);
for ($i = 0; $i < $total_rows; $i++) {
   $row = db2_fetch_assoc($stmt);
   ... do stuff ...
}
Comments