php - multiple tables in 1 query -
i have 2 tables in database:
bogie table:
+----------+----------+---------+----------+ | bogie_id | train_id | axle_nr | bogie_nr | +----------+----------+---------+----------+ | 1 | 1 | 1 | 1 | | 2 | 1 | 2 | 1 | | 3 | 1 | 3 | 2 | | 4 | 1 | 4 | 2 | +----------+----------+---------+----------+
axle table:
+---------+----------+------+----------+ | axle_id | train_id | axle | distance | +---------+----------+------+----------+ | 1 | 1 | 1 | 2500 | | 2 | 1 | 2 | 5000 | | 3 | 1 | 3 | 2500 | +---------+----------+------+----------+
now, want show axles bogie table (4) , distances axle table (3)
i made query (don't mind names):
function hopethisworks(){ $sql = "select * axle 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 * bogie 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; }
now, when enter this:
$testingggg = $database->hopethisworks(); echo $testingggg['bogie']['axle_nr'];
i result: "1"
wich becuase first axle_nr in bogie table 1.
however, wana show 4 instead of 1. make loop:
<?php $testingggg = $database->hopethisworks(); foreach($testingggg $testingggg){ echo $testingggg['bogie']['axle_nr']; } ?>
i expect result be: 1 2 3 4
instead of that, get:
notice: undefined index: bogie in...
how remove error, , show numbers 1, 2, 3, 4?
edit:
the join query had:
function axleees() { $sql = "select ti.axle_nr, ti.train_id, ti.bogie_nr, uti.axle_id, uti.train_id, uti.axle, uti.distance bogie ti join axle uti on ti.train_id = uti.train_id ti.train_id = :train_id"; $sth = $this->pdo->prepare($sql); $sth->bindparam(":train_id", $_get["train_id"], pdo::param_int); $sth->execute(); return $sth->fetchall(); }
what you're getting here not want do. when you're executing hopethisworks()
you're getting array first row of bogie , first row of axle (or second or nth, depending on how mysql orders it)
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
that has 2 rows , 4 elements in each. so, when call res['bogie']['axle_nr'] first time works, because reading first row (res['bogie']
), second time reading second row (res['axle']
) , crashes because you're asking index not defined there.
for want do, guess reading results query should better use join , execute loop this
$i = 0; $aux = $sth->fetch(pdo::fetch_assoc); while ($aux){ $res[i]=$aux; }
Comments
Post a Comment