MS SQL Server Concepts and Programming Question: Download MS SQL Server PDF
PHP ODBC - How To Loop through Returning Rows?
Answer:
The best way to query tables and loop through returning rows is to run a SELECT statement with the odbc_exec() function, catch the returning object as a result set, and loop through the result with odbc_fetch_array() function in a while loop as shown in the following sample PHP script:
<?php
$con = odbc_connect('ggl_SQL_SERVER','sa','GlobalGuideLine');
$sql = "SELECT id, url, time FROM ggl_links";
$res = odbc_exec($con, $sql);
while ($row = odbc_fetch_array($res)) {
print($row['id'].",".$row['url'].",".$row['time']." ");
}
odbc_free_result($res);
odbc_close($con);
?>
Using odbc_fetch_array() is better than other fetch functions, because it allows you to access field values by field names. If you run this script, you will see all rows from the ggl_links table are printed on the screen:
101,globalguideline.com,
102,globalguideline.com/sql,
1101,globalguideline.com/html,
1102,globalguideline.com/xml,
2101,globalguideline.com/xslt,
2102,globalguideline.com/seo,
Don't forget to call odbc_free_result($res). It is important to free up result set objects as soon as you are done with them.
<?php
$con = odbc_connect('ggl_SQL_SERVER','sa','GlobalGuideLine');
$sql = "SELECT id, url, time FROM ggl_links";
$res = odbc_exec($con, $sql);
while ($row = odbc_fetch_array($res)) {
print($row['id'].",".$row['url'].",".$row['time']." ");
}
odbc_free_result($res);
odbc_close($con);
?>
Using odbc_fetch_array() is better than other fetch functions, because it allows you to access field values by field names. If you run this script, you will see all rows from the ggl_links table are printed on the screen:
101,globalguideline.com,
102,globalguideline.com/sql,
1101,globalguideline.com/html,
1102,globalguideline.com/xml,
2101,globalguideline.com/xslt,
2102,globalguideline.com/seo,
Don't forget to call odbc_free_result($res). It is important to free up result set objects as soon as you are done with them.
Previous Question | Next Question |
PHP ODBC - What Is a Result Set Object Returned by odbc_exec()? | PHP ODBC - How To Update Existing Rows in a Table? |