我的数据库中有2个表:
转向架表:
Clonable
Axle 表:
+----------+----------+---------+----------+
| bogie_id | train_id | axle_nr | bogie_nr |
+----------+----------+---------+----------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 1 |
| 3 | 1 | 3 | 2 |
| 4 | 1 | 4 | 2 |
+----------+----------+---------+----------+
现在,我想显示转向架工作台(4)的轴和距离工作台(3)的距离
我提出了一个问题(不要介意这些名字):
+---------+----------+------+----------+
| axle_id | train_id | axle | distance |
+---------+----------+------+----------+
| 1 | 1 | 1 | 2500 |
| 2 | 1 | 2 | 5000 |
| 3 | 1 | 3 | 2500 |
+---------+----------+------+----------+
现在,当我输入此内容时:
function hopethisworks(){
$sql = "SELECT * FROM axle WHERE train_id = :train_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':train_id', $_GET['train_id'], PDO::PARAM_INT);
$sth->execute();
$res['axle'] = $sth->fetch(PDO::FETCH_ASSOC);
$sql = "SELECT * FROM bogie WHERE train_id = :train_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':train_id', $_GET['train_id'], PDO::PARAM_INT);
$sth->execute();
$res['bogie'] = $sth->fetch(PDO::FETCH_ASSOC);
return $res;
}
我得到了结果:“1”
这很好,因为转向架表中的第一个 axle_nr 是1。
然而,我wana显示4而不是1。 所以我做了一个循环:
$testingggg = $database->hopethisworks();
echo $testingggg['bogie']['axle_nr'];
我希望结果为: <?php
$testingggg = $database->hopethisworks();
foreach($testingggg as $testingggg){
echo $testingggg['bogie']['axle_nr'];
}
?>
但不是那样,我得到:
注意:未定义的索引:bogie in ...
如何删除错误,并显示数字1,2,3,4?
修改
我的加入查询:
1 2 3 4
答案 0 :(得分:1)
你在这里得到的不是你想要做的。当您执行hopethisworks()
时,您获得的是第一排转向架和第一排轴(或第二行或第n行,取决于mysql如何命令)的数组
res['bogie']['bogie_id']=1
res['bogie']['train_id']=1
res['bogie']['axel_nr']=1
res['bogie']['bogie_nr']=1
res['axle']['axle_id'] = 1
res['axle']['train_id'] = 1
res['axle']['axle'] = 1
res['axle']['distance'] = 2500
每个都有2行和4个元素。所以,当你第一次调用res [&#39; bogie&#39;] [&#39; axle_nr&#39;]时,因为正在读取第一行(res['bogie']
),但是第二次它是从第二行(res['axle']
)读取然后崩溃,因为你要求索引在那里没有定义。
对于你想要做的事情,我想它是从查询中读取所有结果你应该更好地使用JOIN然后执行这样的循环
$i = 0;
$aux = $sth->fetch(PDO::FETCH_ASSOC);
while ($aux){
$res[i]=$aux;
}