duanhan3067 2011-08-23 05:03
浏览 11
已采纳

mysql查询和php - 如何实现这个?

Okay, so I have a table, with 20 fields named q1, q2, q3 all the way to q20

These fields contain answers, which is a number out of 10.

I want to basically choose 10 questions at random, and do some maths and the php to display it on page.

Here is what I have so far:

$selector = "10218";
/* Work out how many rows to divide by */
$nr = mysql_query("SELECT * FROM `reviews` WHERE `selector` = '" . $selector . "'");
$nr = mysql_num_rows($nr);
/* Get the total sum of answers for question 1  */
$q1 = mysql_query("SELECT sum(`q1`) AS `sum` FROM `reviews` WHERE `selector` = '" . $selector. "'");
$q1 = mysql_fetch_array($q1);
$q1 = $q1['sum'] / $nr;
echo "q1 avg is " . round($q1);

Basically, we want to do this for 10 questions - at random.

We don't want to have to write this code out 20 times, as it is quite strenuous and we want to do some sort of "array" to contain the questions in, and then a for each loop to loop 10 times with a random question?

We want to end up with:

q1 avg is 8
q2 avg is 4
q9 avg is 7
q4 avg is 8
q14 avg is 4
q18 avg is 6
q12 avg is 3
q7 avg is 10
q20 avg is 8
q13 avg is 9

How can we go about doing this? If you didn't understand let me know and I'll try rephrase it.

  • 写回答

2条回答 默认 最新

  • dongluo3331 2011-08-23 05:27
    关注

    How about this:

    // ...
    $query = 'SELECT';
    for ( $i = 1; $i <= 20; $i ++ ) {
        $query .= ' SUM(`q' . $i . '`) AS `sum' . $i . '`';
    }
    $query .= 'FROM `reviews` WHERE `selector` = "' . $selector . '"';
    
    $q1 = mysql_query( $query );
    $q1 = mysql_fetch_array( $q1 );
    foreach ( array_rand( $q1, 10 ) as $col => $sum ) {
        echo $col . ' is ' . $sum . '<br />';
    }
    

    By the way, the sum is not the average :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据