In the previous examples, we're outputting data to the browser in a specific way. That's not the only way to output data to the browser. Your data output strategy will be dictated by the project. Typically, if a project is already using a particular style of output, you want to continue using that style, just for consistency's sake. There is no right or wrong way to output data, unless that code leads to insecure practices.
When developing secure applications, the more consistent you can make your code, the better. Consistency can lead to more secure applications because you start to follow patterns. Patterns are easy to recognize. It can also lead to easier identification of insecure code practices in later code reviews and security audits.
Let's try a different code output method.
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) {
?><div><?= $res["lastName"] ?>, <?= $res["firstName"] ?> in <?= $res["state"] ?></div><?php
}
In this output code, we're using the PHP echo shorthand, which is <?= ?>. If you place a variable inbetween the <?= and ?>, it will send the contents of that variable to the browser.
Another example is using PHP HereDocs. HereDocs are interesting in that anything between the start and end of the HereDoc is output to the browser. A HereDoc is started with three less than symbols aka <<<. The end of the HereDoc must not contain any spaces or tabs at the beginning of the line, as you'll see below:
This code should be put into index.php in your webroot directory.
// echo the results to the browser
foreach ($results as $res) {
echo <<< THEEND
<div>{$res["lastName"]}, {$res["firstName"]} in {$res["state"]}</div>
THEEND;
}
In the code above, the curly braces {} are short hand for "insert the variable here in the output."
And one more example is to just use a string with embedded variables, like the following:
This code should be put into index.php in your webroot directory.
// echo the results to the browser
foreach ($results as $res) {
echo "<div>{$res["lastName"]}, {$res["firstName"]} in {$res["state"]}</div>";
}
This last example, feels similar to the HereDoc method, but with a little less boilerplate and typing. In our examples ahead, we'll be using a variety of methods to output data to the browser.