I'm in the process of converting a quite large existing webapp from the old mysql_ library to the new PDO class. Since it is a quite large webapp and this necessary change popped up quite late in an ongoing project (limitation of mysql_ functions and stored procedures) I have decided for now to just create custom functions which replace the old mysql_ functions and do a search/replace over the whole webapp.
As a reference, my queries are executed as follows:
function MysqlQuery($SqlQuery)
{
global $MysqlPDO; //$MysqlPDO is initialized in an earlier called functions which creates the database connection object
$SqlResult = $MysqlPDO->prepare($SqlQuery,array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); //tried setting a scrollable cursor but this doesnt seem to work...
$SqlResult->execute();
return $SqlResult;
}
So far the only thing I can't get solved is to find a good alternative to the old mysql_result() function. Off course here and elsewhere on the net there are ample examples of so-called mysql_result() replacements, but so far I've found none that works when being called multiple times to fetch the same row.
I first started out with this custom function
function MysqlResult($SqlResult, $RowNumber, $FieldName = 0)
{
$RowArray = $SqlResult->fetch(PDO::FETCH_BOTH,PDO::FETCH_ORI_ABS,$RowNumber);
return $RowArray[$FieldName];
}
However when I call this function more than once, it will only work the first time, as the 2nd time $SqlResult->fetch()
is called, it returns false
, like so:
$SqlQuery = "SELECT 'TEST' AS Test";
$SqlResult = MysqlQuery($SqlQuery);
var_dump(MysqlResult($SqlResult,0,"Test"));
var_dump(MysqlResult($SqlResult,0,"Test"));
var_dump(MysqlResult($SqlResult,0,"Test"));
var_dump(MysqlResult($SqlResult,0,"Test"));
var_dump(MysqlResult($SqlResult,0,"Test"));
This will output the following:
string 'TEST' (length=4)
null
null
null
null
I then decided to use the PDOStatement::fetchAll
method in my custom MysqlResult()
function, like so:
function MysqlResult($SqlResult,$RowNumber,$FieldName = 0)
{
$ResultArray = $SqlResult->fetchAll();
$RowArray = $ResultArray[$RowNumber];
return $RowArray[$FieldName];
}
But this produces exactly the same output as my first attempt.
The problem is that in my existing webapp, there are a few occurances where mysql_result is used to get the same SQL output twice or more times. While I perfectly realize this is not nice coding, I don't want to go in and rewrite those parts at this point. Am I to believe that the shiny new MySQL PDO class is more limited than the old mysql_ functions??