ODBC prepared statements in PHP

psynnott picture psynnott · Apr 22, 2011 · Viewed 13.3k times · Source

I'm trying to use odbc_prepare and odbc_execute in PHP as follows:

$pstmt=odbc_prepare($odb_con,"select * from configured where param_name='?'");
$res=odbc_execute($pstmt,array('version'));
var_dump($res);  //bool(true)
$row = odbc_fetch_array($pstmt);
var_dump($row);  //bool(false)

The first var_dump returns true so the execute succeeds, but there is no row returned. A row does indeed exist with the param_name = 'version'. Why is no row returned?

To make things interesting, I ran another very simple example in php using a prepared insert.

$pstmt=odbc_prepare($odb_con,"insert into tmp1 values(?,'?')");

This line, by itself, inserted a row into the database!! Surely this is just wrong? The data entered was col 1 = blank, col 2 = ?

Any advice on where to start fixing this would be appreciated, thanks.

Edit: This is in PHP 5.2.8

Answer

Michael picture Michael · Apr 22, 2011

Try removing the single quotes from the query string and adding them to the parameter value itself:

$pstmt=odbc_prepare($odb_con,"select * from configured where param_name=?");
$res=odbc_execute($pstmt,array(" 'version'"));
var_dump($res);  //bool(true)
$row = odbc_fetch_array($pstmt);
var_dump($row);  //bool(false)

The single space character at the beginning of the parameter value is very important--if the space is not there, it will treat the variable as a path to a file.

From http://www.php.net/manual/en/function.odbc-execute.php:

If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name.