Wednesday, April 21, 2010

Invalid cursor state, SQL state 24000 in SQLExecDirect

This worked when I was running Windows (WAMP), but when I moved to Ubuntu it started throwing this error:
Warning: odbc_exec() [function.odbc-exec]: SQL error: [unixODBC][FreeTDS][SQL Server]Invalid cursor state, SQL state 24000 in SQLExecDirect Error in SQL

The problem was that I had an odbc_exec inside another one.

Something like this:
$sql="SELECT column_a FROM table";
$rs=odbc_exec($conn,$sql);

while (odbc_fetch_row($rs)) {
$sql2="SELECT * FROM table WHERE column_b = " . odbc_result($rs,"column_a");
$rs2=odbc_exec($conn,$sql2); //would not work
}

What I did to fix it:
$sql="SELECT column_a FROM table";
$rs=odbc_exec($conn,$sql);

$arr = array(); //you need this in case it's empty, otherwise the foreach will throw an error

while( $col = odbc_fetch_array($rs) ) {
array_push($arr, $col);
}

foreach ($arr as $value) {
$sql2="SELECT * FROM table WHERE column_b = " . $value["column_a"];
$rs2=odbc_exec($conn,$sql2);
}

You are just going throw the array instead of the result set... Straight forward, but wanted to share it :)

1 comment: