PDA

View Full Version : Select in Oracle 10g doubles output


nst
09-28-2006, 12:41 PM
The code below connects to an Oracle 10g database, but it produces twice the output of every table



<?php

// CONNECT to the database
$conn = oci_connect('stocks', 'stocks');
if (!$conn) {
$e = oci_error();
print htmlentities($e['message']);
exit;
}

// SELECT and output on the screen
$query = 'SELECT * FROM STOCKS';
$stid = oci_parse($conn, $query);
if (!$stid) {
$e = oci_error($conn);
print htmlentities($e['message']);
exit;
}
$r = oci_execute($stid, OCI_DEFAULT);
if (!$r) {
$e = oci_error($stid);
echo htmlentities($e['message']);
exit;
}
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) {
print '<tr>';
foreach ($row as $item) {
print '<td>'.($item?htmlentities($item):'&nbsp;').'</td>';
}
print '</tr>';
}
print '</table>';

oci_close($conn);
?>



Output

T100_S T100_S
T101_S T101_S
T102_S T102_S

although it should be

T100_S
T101_S
T102_S

Fumigator
09-28-2006, 02:53 PM
You're telling it to:

print '<td>'.($item?htmlentities($item):'&nbsp;').'</td>';

raf
09-28-2006, 03:10 PM
he uses the
$item?htmlentities($item):'&nbsp;'

as shorthand for

if ($item){
echo htmlentities($item);
}else{
echo '&nbsp;';
}

so that should be correct.

Fumigator
09-28-2006, 03:18 PM
Whoops sorry that's me not quite awake... :o

nst
09-28-2006, 03:32 PM
Correct. Also a simple echo didn't help. Why?
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) {
print '<tr>';
foreach ($row as $item) {
echo $item;
}
print '</tr>';
}
print '</table>';

Of course a direct query to the database does not produce the error.

Maybe it has to do with the Predefined Constants like 'OCI_DEFAULT'

Any idea what exactly these are?

Fumigator
09-28-2006, 03:35 PM
OK maybe this answer will be a little more thought out and intelligent. :D

You are looping through every index in the array created by oci_fetch_array(). the function oci_fetch_array() creates both a numeric index and an associative index, so you are getting two indices with the same value in the loop.

Use oci_fetch_row() or oci_fetch_assoc() to limit the number of indices to one per row.

nst
09-28-2006, 04:17 PM
Fumigator, it's ovbious you are awake now... It worked!

Actually, output is equal correct with either one of the following
while ($row = oci_fetch_row($stid)) {

while ($row = oci_fetch_assoc($stid)) {

Thank you. :)