Doing Joins In PHP
Doing a join within a PHP PDO query is just like you would imagine. In our next example, we'll get the state field, so we know where our employees operate from.
This code should be put into index.php in your webroot directory.
<?php
// make a connection to the MySQL server
$db = new PDO("mysql:host=localhost;dbname=employees;", "[username]", "[password]");
// prepare a query
$prep = $db->prepare("select lastName, firstName, state from names n left join addresses a on n.id=a.nameId order by state");
// execute the query
$prep->execute();
// fetch the results and put them into a variable
$results = $prep->fetchAll();
// echo the results to the browser
foreach ($results as $res) {
echo "<div>" . $res["lastName"] . ", " . $res["firstName"] . " in " . $res["state"] . "</div>";
}
We basically did our left join and added the field state to the query and the output.