问题
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