Saturday, May 24, 2008

Running a command for each value comming back from an ODBC query in PHP

I have a need to read an ODBC datasource and run a query on a particual table. For each unique value of the table, I need to run a command in the shell.

Here is anexample:


<?php
$values = Array() ;
$command = "echo" ; /* for the example purposes the command is echo */
$columnName = "state" ; /* just for this example */

$hdbc = odbc_connect ( "dsn-name", NULL, NULL ) ;
if ( $hdbc != NULL )
{
$hstmt = odbc_prepare(
$hdbc
, "select distinct " . $columnName . " from tablename"
) ;
if ( $hstmt != NULL )
if ( odbc_execute( $hstmt ))
{
while ( odbc_fetch_row( $hstmt ))
$values[] = odbc_result( $hstmt, 1 ) ;
}
else
printf( "*** Unable to execute\n" ) ;
else
printf( "*** Unable to prepare the query.\n" ) ;

odbc_close( $hdbc ) ;
}
else
printf( "*** Unable to connect\n" ) ;

foreach ( $values as $value )
system( $command . " \"" . $value . "\"" ) ;
?>

No comments: