使用PDO将MYSQL查询的结果打印两次 [英] Results of MYSQL query printed twice using PDO

查看:52
本文介绍了使用PDO将MYSQL查询的结果打印两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名老师,并且我有一个名为'gabber'的mysql表,该表可容纳数十名学生测验.这些字段是锻炼",真实姓名",得分",开始时间"和结束时间".如果学生完成了不止一种类型的测验,则该测验将在表中显示为另一行,但当然具有不同的锻炼"值.

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.

无论如何,PHP代码除了将每个值打印两次外,都可以正常工作.即名称被打印两次,每个分数也被打印两次.我知道我的查询绝对正确(已在phpmyadmin中测试),但是我认为嵌套的for循环出了问题.我尝试阅读有关查询返回的PDOstatement的信息,但我听不懂.我很欣赏stackoverflower上还有其他有关两次打印"的文章,但它们无法帮助我解决这个问题.

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>';
?>

推荐答案

连接到PDO时,请采用这种方式

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

这篇关于使用PDO将MYSQL查询的结果打印两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆