PHP/MySQLi Joins/Names/Referencing same table for different values

I have a generic table that holds references for various pages on the site.  Keyed kind of like...

column 1 -> Page ID
column 2 -> Page Name

and I'm writing a SQL query to grab different values...one of which needs to be the name of one page...and then based upon that value the grab a second value from that same table.

Kind of like...

$query = "SELECT * FROM mytable t1
		INNER JOIN tblreservation t2 on t2.key = t1.key
		INNER JOIN primarytable t3 on t3.key = t2.key
		INNER JOIN tblagent t3 on t3.key = t1.key
		INNER JOIN primarytable t4 on t4.key = t3.key

		WHERE t1.key = $fmid";
		$result = $con->query($query);

Open in new window


I tried saying in PHP

<?
while($row = $result->fetch_assoc()) {
echo ($row['t2.title']);
echo($row['t4.title']);
}
?>

to no avail...  What am I missing?  :)
LVL 2
erzoolanderAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Why not just run two queries?  Get the independent information in the first query and use it to get the dependent information in the second query.
0
Julian HansenCommented:
What you have to do is alias the fields that have the same name - something like this

$query = "SELECT t1.*, t2.title as t2Title, t4.title AS t4Title 
FROM mytable t1
		INNER JOIN tblreservation t2 on t2.key = t1.key
		INNER JOIN primarytable t3 on t3.key = t2.key
		INNER JOIN tblagent t3 on t3.key = t1.key
		INNER JOIN primarytable t4 on t4.key = t3.key

		WHERE t1.key = $fmid";
		$result = $con->query($query);

Open in new window


In the case of table t2 and t4 you will have to also explicitly name each field you want to be returned by the query because you are aliasing one of the fields unless you do something like

select t2.title as t2Title, t4.title as t4Title, * ...

Open in new window


In your code you can then do this

while($row = $result->fetch_assoc()) {
  echo ($row['t2Title']);
  echo($row['t4Title']);
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
erzoolanderAuthor Commented:
Thanks for the help.  Got it working now.

Before I assign points - have a question for Ray because he's always got good input on things here.

Generally, I like to try and build "one query to rule them all" types of things if possible...and I see running secondary queries as being inefficient.  Now, I think you're drastically better at this than I am.  Are secondary queries not viewed as being inefficient by others?
0
Ray PaseurCommented:
Secondary queries are always "inefficient" in some measure, but the real question is "what is the cost of inefficiency?"  If it adds several seconds to your page-build process, then it's worth optimizing.  If you're interested in an efficient approach that does not require query optimization, consider cacheing the responses.  I would probably attach a timer to the script and try it to see how much might be gained by using a single query.  Here's how you can do that.

<?php // demo/class_Stopwatch.php
error_reporting(E_ALL);

// START THE TIMER
$t = new StopWatch;
$t->start();

// DO SOME ACTIVITY THAT YOU WANT TO TIME
$x = file_get_contents('https://google.com/');

// GET A READOUT FROM THE TIMER
echo $t->readout();

// RESET THE TIMER
$t->reset();


// A SCRIPT TIMER FOR ALL OR PART OF A SCRIPT PHP 5+
// MAN PAGE http://php.net/manual/en/function.microtime.php
class StopWatch
{
    protected $a; // START TIME
    protected $s; // STATUS - IF RUNNING
    protected $z; // STOP TIME

    public function __construct()
    {
        $this->a = array();
        $this->s = array();
        $this->z = array();
    }

    // A METHOD TO PROVIDE A FINAL READOUT, IF NEEDED
    public function __destruct()
    {
        $ret = $this->readout();
        if (!$ret) return FALSE;
        echo
          __CLASS__
        . '::'
        . __FUNCTION__
        . '() '
        ;
        echo "<b>$ret</b>";
        echo PHP_EOL;
    }

    // A METHOD TO REMOVE A TIMER
    public function reset($name='TIMER')
    {
        // RESET ALL TIMERS
        if ($name == 'TIMER')
        {
            $this->__construct();
        }
        else
        {
            unset($this->a[$name]);
            unset($this->s[$name]);
            unset($this->z[$name]);
        }
    }

    // A METHOD TO CAPTURE THE START TIME
    public function start($name='TIMER')
    {
        $this->a[$name] = microtime(TRUE);
        $this->z[$name] = $this->a[$name];
        $this->s[$name] = 'RUNNING';
    }

    // A METHOD TO CAPTURE THE END TIME
    public function stop($name='TIMER')
    {
        $ret = NULL;

        // STOP ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                // IF THIS TIMER IS STILL RUNNING, STOP IT
                if ($this->s[$name])
                {
                    $this->s[$name] = FALSE;
                    $this->z[$name] = microtime(TRUE);
                }
            }
        }

        // STOP ONLY ONE OF THE TIMERS
        else
        {
            if ($this->s[$name])
            {
                $this->s[$name] = FALSE;
                $this->z[$name] = microtime(TRUE);
            }
            else
            {
                $ret .= "ERROR: CALL TO STOP() METHOD: '$name' IS NOT RUNNING";
            }
        }

        // RETURN AN ERROR MESSAGE, IF ANY
        return $ret;
    }

    // A METHOD TO READ OUT THE TIMER(S)
    public function readout($name='TIMER', $dec=3, $m=1000, $t = 'ms', $eol=PHP_EOL)
    {
        $str = NULL;

        // GET READOUTS FOR ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                $str .= $name;

                // IF THIS TIMER IS STILL RUNNING UPDATE THE END TIME
                if ($this->s[$name])
                {
                    $this->z[$name] = microtime(TRUE);
                    $str .= " RUNNING ";
                }
                else
                {
                    $str .= " STOPPED ";
                }

                // RETURN A DISPLAY STRING
                $lapse_time = $this->z[$name] - $start_time;
                $lapse_msec = $lapse_time * $m;
                $lapse_echo = number_format($lapse_msec, $dec);
                $str .= " $lapse_echo $t";
                $str .= $eol;
            }
            return $str;
        }

        // GET A READOUT FOR ONLY ONE TIMER
        else
        {
            $str .= $name;

            // IF THIS TIME IS STILL RUNNING, UPDATE THE END TIME
            if ($this->s[$name])
            {
                $this->z[$name] = microtime(TRUE);
                $str .= " RUNNING ";
            }
            else
            {
                $str .= " STOPPED ";
            }

            // RETURN A DISPLAY STRING
            $lapse_time = $this->z[$name] - $this->a[$name];
            $lapse_msec = $lapse_time * $m;
            $lapse_echo = number_format($lapse_msec, $dec);
            $str .= " $lapse_echo $t";
            $str .= $eol;
            return $str;
        }
    }
}

Open in new window

0
Julian HansenCommented:
Databases are designed to efficiently deal with data. If you have designed your database properly then there should be no reason why you don't leverage the full potential of the database engine.

Where possible you should be using the database to return the values you need in one query. Sometimes this is not possible and you have to resort to script and / or supplementary queries to achieve what needs to be done but often this points back to the design of the database.

Bottom line is use the best tool for the job and then leverage that tool to do as much of the grunt work as possible.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.