mysql查询中的循环数组和结果

时间:2014-09-18 13:04:44

标签: php mysql

我正在尝试循环一个mysql查询并在新行上显示每个结果。我知道我缺少一些骰子,我需要在mysql中设置变量吗?

$value = array(B1,B2,B3,B4);
$query = "SELECT SUM($value[0]) AS ".$value[0]."_SUM, "
    ."SUM(answer_value) AS ".$value[0]."_ANSWER_SUM "
    ."FROM questions q JOIN answers a ON q.question_id = a.question_id "
    ."WHERE $value[0]=1";

$result = mysqli_query($con, $query);

while($row = mysqli_fetch_array($result)) {
    echo "<tr><td>".$value[0]."</td>";
    echo "<td>".$row['B1_ANSWER_SUM']."</td>";  
    echo "<td>".$row['B1_SUM'] ."</td>"; 
    echo '</tr>' ;  
}

我想得到这个结果:

B1 B1_ANSWER_SUM B1_SUM
B2 B2_ANSWER_SUM B2_SUM
B3 B2_ANSWER_SUM B2_SUM

1 个答案:

答案 0 :(得分:0)

您需要循环遍历数组并查询数组中的每个项目。见下文:

$value = array('B1', 'B2', 'B3', 'B4');

foreach ($value as $v) {
    $query = "SELECT SUM($v) AS ".$v."_SUM, SUM(answer_value) AS ".$v."_ANSWER_SUM FROM questions q JOIN answers a ON q.question_id = a.question_id WHERE $v=1";

    $result = mysqli_query($con, $query);

    while($row = mysqli_fetch_array($result)) {
        echo "<tr><td>".$v."</td>";
        echo "<td>".$row[$v.'_ANSWER_SUM']."</td>";  
        echo "<td>".$row[$v.'_SUM'] ."</td>"; 
        echo '</tr>' ;  
    }
}