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'];
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!