0

I'm trying to move out all of my php legacy code to PDO Statments. All seems it works great, but I commonly use mysql_data_seek function in cases like this, and I'm trying to find a way for PDO, but I honestly don't find anything related with this. This is what I actually do (without PDO)

$query = mysql_query("SELECT * sometable");
$array = mysql_fetch_assoc($query);

$name = $array['name']

// $name is returned well, but now I want to loop it, so I use mysql_data_seek to reset the query. I want just one row, not more.

mysql_data_seek($query, 0);

// now i can loop

while($arr = mysql_fetch_assoc($array)){
    echo "name: " . $arr[$arr];
}

So now I'm trying to do something like this:

$query = $conn->query("SELECT * sometable");
$array = $query->fetch();

$name = $array['name'];

// It outputs just one row, that's what I really want to, so I want to loop it now.

foreach($query->fetchAll() as $loop){
    echo $loop['name']
}

// This time I don't get anything...

Any suggestions? THANKS!

user1978142
  • 7,946
  • 3
  • 17
  • 20
  • 1
    If you're retrieving all results anyway, why don't you just keep it in an array, and use row `[0]["name"]` then initially. – mario Apr 27 '14 at 16:03

1 Answers1

0

There is no sense in fetching the same data twice.
You did it wrong with mysqli and you shouldn't repeat it with pdo.

$query = $conn->query("SELECT * sometable");
$array = $query->fetchAll();
foreach($array as $row){
    echo $row['name'];
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345