I'm trying to loop a mysql query and display every result on new row. I know i'm missing some pices, do i need to SET variable in mysql instead?
$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>' ;
}
I would like to get this result:
B1 B1_ANSWER_SUM B1_SUM
B2 B2_ANSWER_SUM B2_SUM
B3 B2_ANSWER_SUM B2_SUM
You need to loop through your array and query each item in the array. See below:
$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>' ;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.