我想显示此结果
Bodypart1,Bodypart2
我的代码:
$sql = "
SELECT x.*
, b.bodypart_name bodypart
FROM exercises x
, equipments e
, bodyparts b
WHERE x.exercise_bodypart = b.bodypart_id
";
$statement = $pdo->prepare($sql);
$statement->execute();
$exercises = $statement->fetchAll();
?>
<table>
<th>Bodypart</th>
</tr>
</thead>
<?php foreach($exercises as $exercise): ?>
echo $exercise['bodypart'];
?></span></td>
</tr>
<?php endforeach; ?>
</table>
答案 0 :(得分:0)
$statement->fetchAll(PDO::FETCH_ASSOC)
//将结果提取到关联数组中。
你也忘记了开场<td><span>
答案 1 :(得分:0)
首先,您的数据库结构有点偏。
#Your excercise_bodypart field contains multiple keys, remove the field.
ALTER TABLE test_answer_override
DROP COLUMN exercise_bodypart;
#Build a bridge table which will establish a many to many relationship between exercises and bodyparts.
CREATE TABLE exercise_body_part
exercise_id INT NOT NULL,
bodypart_id INT NOT NULL,
PRIMARY KEY (exercise_id,bodypart_id),
KEY exercise_id (exercise_id),
KEY bodypart_id (bodypart_id),
CONSTRAINT fk_exercise_bodypart FOREIGN KEY (`bodypart_id`) REFERENCES `bodyparts`(`bodypart_id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_bodypart_exercise FOREIGN KEY (`exercise_id`) REFERENCES `exercise`(`exercise_id`) ON UPDATE CASCADE ON DELETE CASCADE;
#Insert the rows needed that were removed with the deletion of exercise_bodypart field in step one above.
INSERT INTO excercise_body_part(exercise_id,bodypart_id) VALUES(5,8),(5,9);
你在这里缺少的是一个加入。出于这个问题的目的,尽管没有这样规定,我将假设你真的想要的不只是列出身体部分,但也会列出练习。现在让我们来解决这个问题:
SELECT
exercises.*,
bodyparts.bodypart_name AS 'bodypart'
FROM bodyparts
JOIN exercise_body_part ON bodyparts.bodypart_id=exercise_body_part.bodypart_id
JOIN excercise ON exercise_bodypart.exercise_id=exercise.exercise_id
ORDER BY bodypart;
就你的HTML而言,看起来你有一个错误,你不匹配你的PHP标签。也许这就是你要找的东西?
<table>
<tr>
<th>Body Part</th>
<th>Exercises</th>
<tr>
<?php
$currentBodypart="";
foreach($exercises as $exercise){
if($currentBodypart!=$exercise['bodypart']){
$currentBodypart=$exercise['bodypart'];
//create a new row and add the first column with the bodypart name ?>
<tr>
<td><?=$exercise['bodypart'];?></td><td>
<?php } else { ?>
<table border="1">
<tr>
<th>Title</th>
<th>Reps</th>
</tr>
<tr>
<td><?=$exercise['exercise_title'];?></td>
<td><?=$exercise['exercise_reps'];?></td>
</tr>
</table>
<?php
}
if($currentBodypart!=$exercise['bodypart']){
//close of the cell containing exercises and end the new row ?>
</td></tr>
<?php }
}?>
</table>
没有PHP的HTML可能看起来像这样:
<html>
<body>
<table border="1">
<tr>
<th>Bodypart</th>
<th>Exercises</th>
<tr>
<tr>
<td>Bodypart 1</td>
<td>
<table>
<tr>
<th>Title</th>
<th>Reps</th>
</tr>
<tr>
<td>Exercise 1</td>
<td>12</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
将您的任务分解成更小的部分,您将获得成功。首先确保查询正在运行。然后确保PHP正常工作,并使用var_dump()函数从数据库中获取数据。然后,尝试使用简单的HTML示例来使模板正确。最后,通过PHP将从MySQL中提取的数据插入到您的页面中。