May 11, 2012
Set variable from alias in SQL query
Question by Sherif
I have a simple JOIN query:
$lstCheck = $dbWHMCS->query('SELECT * FROM tblmonitorports mp
INNER JOIN tblmonitorhosts h ON h.hst_id = port_mon
INNER JOIN tblhosting ho ON ho.id = h.hst_serverid
INNER JOIN tblclients cl ON cl.id = ho.userid');
while ($data = $lstCheck->fetch())
{
$serveridx = $data['ho.id'];
$clientid = $data['cl.id'];
}
My problem is that I have an “id” column in both the tblhosting and tblclients tables, so my variables both have the same id. I tried to set it using an alias in the example above (ho. and cl.) but it doesn’t work. How can I do this in the example above?
Thank you!
Answer by Mirko
How about this? (a bit rusty on php details, but this should do it):
$lstCheck = $dbWHMCS->query('SELECT ho.id hid, cl.id cid FROM tblmonitorports mp
INNER JOIN tblmonitorhosts h ON h.hst_id = port_mon
INNER JOIN tblhosting ho ON ho.id = h.hst_serverid
INNER JOIN tblclients cl ON cl.id = ho.userid');
while ($data = $lstCheck->fetch())
{
$serveridx = $data['hid'];
$clientid = $data['cid'];
}
Answer by Starx
You are selecting the records, with a wild card *
, so you can’t select the fields like that.
As per your query h.hst_serverid
& ho.userid
have the exact same value as you want. SO simply do this
while ($data = $lstCheck->fetch())
{
$serveridx = $data['hst_serverid'];
$clientid = $data['userid'];
}
However, selecting specific rows might sound better too
$lstCheck = $dbWHMCS->query('SELECT ho.id hid, cl.id cid, ....');
while ($data = $lstCheck->fetch())
{
$serveridx = $data['hid'];
$clientid = $data['cid'];
}