I want display a table content along with column names.
I have used SQL query for columns
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable"
and I have used SQL query for content
"SELECT * FROM $mytable"
Both are working fine. Only thing is that, order of columns is different. Some times its just reverse. sometimes it is reverse with some shift of 2-3 columns depending on number of column in $mytable.
You need to include an order by when you query ALL_TAB_COLUMNS
on COLUMN_ID
:
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable ORDER BY COLUMN_ID".
This orders the columns by the order created.
Probably a better approach is to simply read the column names from the returned resultset. This means you need only one query:
$conn = oci_connect($username, $password, $connectionString);
$stmt = oci_parse($conn, 'select * from mytable');
oci_execute($stmt);
$headers = false;
while ($row = oci_fetch_assoc($stmt)) {
if (!$headers) {
// this will only output the headers on the first iteration.
print_r(array_keys($row));
$headers = true;
}
print_r($row);
}
Or you could use oci_field_name()
against the resultset but I've always felt the above method is simpler.
Edit: In case there are no results, you won't be able to get the keys (since the array is empty). You can add the following code after the while
loop to handle that:
if (!$headers) {
for ($i = 1; $i <= oci_num_fields($stmt); $i++) {
echo oci_field_name($stmt, $i), PHP_EOL;
}
}