Monday, April 10, 2017

how use mysql_data_seek with PDO?

Leave a Comment

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 tell 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.

4 Answers

Answers 1

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); 

Answers 2

$result = $arrayData[4]; 

is all you need.

Answers 3

If you want the 5th row result you can do like this:

$result = json_decode(json_encode($arrayData[4]), FALSE); var_dump($result); 

or something like this:

$object = new stdClass(); foreach ($array as $key => $value) {     $object->$key = $value; } 

Just curious! why do you need the object form?

EDIT (this will give the object form of the 5th row):

$index = 0; $fifthRow = new stdClass(); while($row = $q->fetch()) {    if($index++==4)         $fifthRow = json_decode(json_encode($row), FALSE); }    

Answers 4

You could do it like this:

$c = 1; $saved=null;  while($row = $q->fetch()){     if($c==4){         $saved = clone $row;     };     $c++;     somethingelse; } 

$saved will then contain the 4th element as an object with almost no extra overhead calculations.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment