问题
I am a teacher and I have a mysql table called 'gabber' which holds scores of student quizzes. The fields are 'Exercise', 'realname, 'Score', 'Start_Time' and 'End_Time'. If a student completes more than one type of quiz, then this will appear as another row in the table, but of course with a different Exercise value.
My code below, which very nearly works, first finds the unique exercise values, and uses these to print the table column headings. These unique exercise values are also used to create the second query, which finds the minimum (i.e. first attempt) score for each student's attempt at each quiz.
Anyway, the php code works EXCEPT for printing each value twice. i.e. the name is printed twice, as is each score. I know that my query is definitely correct (tested in phpmyadmin), but I think things are going wrong in the nested for loop. I have tried reading about PDOstatement which the query returns, but I could not understand it. I appreciate that there are other posts on stackoverflower about "printing twice", but they could not help me solve this.
Any suggestions on how to make this work would be excellent. Thanks, Matt.
<?
$dbh = new PDO("mysql:host=XXX;dbname=gabber", user, pass);
$query2 = "SELECT realname";
echo '<style>table{border-collapse:collapse;}';
echo 'table, td, th{border:1px solid black;}</style>';
echo '<table><tr><td></td>';
foreach($dbh->query('SELECT DISTINCT Exercise FROM a2_physics') as $row) {
echo '<td>';
echo $row[0];
echo '</td>';
$query2.=', MIN( IF( Exercise = "';
$query2.=$row[0];
$query2.='", Score, NULL ) ) AS "';
$query2.=$row[0];
$query2.='"';
}
echo '</tr>';
$query2=$query2.' FROM a2_physics';
$query2=$query2.' GROUP BY realname';
//echo $query2;
foreach($dbh->query($query2) as $row) {
echo '<tr>';
foreach($row as $element)
{
echo '<td>';
echo $element;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
回答1:
When connecting to PDO, do it this way
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
来源:https://stackoverflow.com/questions/17673759/results-of-mysql-query-printed-twice-using-pdo