我有这个php代码for循环,在每一步中,每一个增量都在mysql表中搜索数据aktivnosti
菲律宾比索:

for ($i=1; $i<=30; $i++;){
    $temp = array();
    $temp['ID'] = $i;

// ATTEMP TO GET DATA FROM aktivnosti WHERE id_activity = $i

    $rs1 = $db->prepare('SELECT naziv FROM aktivnosti WHERE id_activity=:idd');
          $rs1->bindParam(':idd', $i);

          $rs1->execute();
          $naz = $rs1->fetchColumn();

          $temp['activity'] =  '<button>'.$naz.'</button>';



    $output['data'][] = $temp;

}
$jsonTable = json_encode($output);

从上面的代码中可以看到,我试图获取每个$i增量的数据,并搜索是否id_activity on table aktivnosti = $i
我只得到一个结果,所以我只得到第一个'naziv',我需要从表aktivnosti获取所有naziv数据,其中id_activity=$I并创建:
<button>$naz[0]<button>
<button>$naz[1]<button>
<button>$naz[2]<button>
<button>$naz[how many times id_activity = $i]<button>

我该怎么做?有什么想法?
对不起我的英语。谢谢

最佳答案

正如上面的评论所指出的,您在这里采取了一种糟糕的做法。您应该能够在一个查询中获取所有这些数据。如果您想要有一个固定的30天的概念,并且每一天都与n记录数相关,那么您可能还需要查看您的模式。我建议两张桌子
日清单

day_id  day_name (or any other day-related data fields)
1       ...
2       ...
...     ...
30      ...

天记录
record_id   day_id   other_data
1           1        ...
2           1        ...
3           3        ...
4           5        ...
...

然后您可以这样查询:
SELECT
    d.day_id AS day_id
    dr.record_id AS record_id
    dr.other_date AS other_data
FROM day_list AS d
LEFT JOIN day_records AS dr
    ON d.day_id = dr.day_id

很抱歉更改了表名,因为不知道您的数据库架构在现实世界中代表什么。
然后进行一个查询,如下所示:
$query = <<<EOT
SELECT
    d.day_id AS day_id
    dr.record_id AS record_id
    dr.other_date AS other_data
FROM day_list AS d
LEFT JOIN day_records AS dr
    ON d.day_id = dr.day_id
EOT;

$rs1 = $db->execute($query);
if (false === $rs1) {
   // something went wrong. perhaps log an error
} else {
   while($row = $rs1->fetch(PDO::FETCH_ASSOC)) {
        $temp = $row;
        // check to see if this date has a record
        if (empty($temp['record_id'])) {
            // this is a day with no associated record.
            // do something
        }
        // not shown - continue to manipulate your $temp as desired
        // then add to output array
        $output['data'][] = $temp
   }
}

10-01 19:56
查看更多