Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use mysql_data_seek with PDO?

Tags:

mysql

pdo

I want use mysql_data_seek with PDO from google search I found that it should looks like this:

$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);

however it's not work, what I do wrong? this is my code:

$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();

$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();

foreach ($arrayData as $row){

    echo $row['name'] ." ";
    echo $row['age'] ."<br>";
}

$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);

I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.

the var_dump result is: bool(false)

any ideas?

EDIT:

thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.

like image 497
Dennis Avatar asked Mar 26 '13 12:03

Dennis


1 Answers

the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'

example:

$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

before use it like this:

$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
like image 68
Dennis Avatar answered Oct 06 '22 01:10

Dennis