我有这个PHP代码 - for循环和每一步,每次增量搜索mysql表中的数据aktivnosti
PHP:
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>
我怎么能这样做?一些想法?
对不起我的意见。感谢答案 0 :(得分:2)
正如上面的评论中指出的那样,你在这里采取了不好的做法。您应该能够在单个查询中获取所有这些数据。如果您希望每天都有与n
个记录数相关的固定数量30天的概念,您可能还需要查看您的架构。我建议两张桌子
day_list
day_id day_name (or any other day-related data fields)
1 ...
2 ...
... ...
30 ...
days_records
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
}
}
答案 1 :(得分:1)
如果您同时需要ID
和activity
:
$sql = <<<EOD
SELECT
id_activity AS ID,
CONCAT('<button>', naziv, '</button>') AS activity
FROM aktivnosti
WHERE id_activity BETWEEN 1 AND 30
ORDER BY id_activity
EOD;
$data = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$jsonTable = json_encode(compact('data'));
如果您只使用activity
:
$sql = <<<EOD
SELECT CONCAT('<button>', naziv, '</button>')
FROM aktivnosti
WHERE id_activity BETWEEN 1 AND 30
ORDER BY id_activity
EOD;
$data = $db->query($sql)->fetchAll(PDO::FETCH_COLUMN, 0);
$jsonTable = json_encode(compact('data'));
答案 2 :(得分:1)
试试这个......
while($naz=$rs1->fetch(PDO::FETCH_OBJ))
{
echo $naz->column1;
echo $naz->column2;
}
而不是
$naz = $rs1->fetchColumn();