Back to examples |
Once you have connected to the database and performed a query you probably want to return the data. The tidiest way to do this is to return the data in an associative array.
Now PHP already has a function that will do this odbc_fetch_array, however, I have had issues with this function on Windows with Access databases where it will not correctly return the column headings. So for a safe version, we create a custom function odbc_fetch_array_custom.
The other thing to note with ODBC and Access is that odbc_num_rows does not actually work properly, it tends to return -1, in which case the easiest way to return rows is to scroll through each row until you reach the end of the data.
|
<?php
function odbc_fetch_array_custom($id_res) {
// Clear our return variable
unset($ar);
// Get the number of fields in the returned result
$colnum = odbc_num_fields($id_res);
// Fill an array with the column headers // We do this here to save API calls.
for($i=1; $i<=$colnum;$i++)$field_name[$i]=odbc_field_name($id_res,$i);
// If we have a result
if (odbc_fetch_row($id_res)) {
// Fill our return array with the column data
for ($i = 1; $i <= $colnum; $i++) $ar[$field_name[$i]] = odbc_result($id_res, $field_name[$i]);
return $ar; } else { return false; } }
?>
|
|
<?php
$db = "monkeys";
// odbc_connect_custom was in part 1
$connection_id = odbc_connect_custom($db);
$query = "SELECT name,amount FROM monkey_types"; $result_id = odbc_exec($connection_id,$query);
while($result=odbc_fetch_array_new($result_id)) { // Do whatever we want with the row print($row["name"]."<br>"); print($row["butt_color"]."<br>"); } ?>
|