Resetting results pointer without mysql_data_seek

好久不见. 提交于 2019-12-12 00:56:23

问题


I want to do two things after fetching a recordset. Print the firstname and lastname from the first record (all records will have same name), then under that, output all of the records for that recordset in a table. The act of fetching the first record moves the pointer up one record, so that won't work. I want to reset the pointer after getting the first & last name off the first record. I'm using PDO, and, besides from what I have read, mysql_data_seek is deprecated.

Here's how I'm currently doing it (inefficient perhaps, as all I am doing is rerunning the same query to get the complete recordset -or is it OK?):

   $query = "SELECT students.*, lessons.lessonname, assignments.assignmentid, assignments.complete, assignments.score    
            FROM lessons INNER JOIN 
            (assignments INNER JOIN students 
            ON assignments.studentid = students.id) 
            ON lessons.lessonid = assignments.lesson
            WHERE (((students.id)=".$_POST['viewstudentdrop']."))";
    $results = $pdo->query($query);
    $row = $results->fetch(); //just get the first record.
    echo 'Assignments for: ' . $row['firstname'] . " " . $row['lastname']. "<br>";        
    $results = $pdodl->query($query); //resets pointer

回答1:


$results = $pdo->query($query);
$data = $results->fetchAll();
$row  = reset($data);
echo 'Assignments for: ' . $row['firstname'] . " " . $row['lastname']. "<br>";        
foreach ($data as $row) {
...


来源:https://stackoverflow.com/questions/14860530/resetting-results-pointer-without-mysql-data-seek

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!