/    Sign up×
Community /Pin to ProfileBookmark

curious about the way this code is written

Hi, im going through a tutorial on php from udemy.com and im curious about the following peice of code on it

[CODE]
<?php

global $connect;

$sql = “SELECT * FROM category”;
$stmt = $connect->query($sql);
while ($daterows = $stmt->fetch()){
$id = $daterows[“id”];
$categoryname = $daterows[“title”];
?>
<option><?php $categoryname; ?> </option>
<?php } ?>
[/CODE]

why does the original author break up the while loop with php tags? i tried it the following way and it worked fine

[CODE]
<?php

global $connect;

$sql = “SELECT * FROM category”;
$stmt = $connect->query($sql);
while ($daterows = $stmt->fetch()){
$id = $daterows[“id”];
$categoryname = $daterows[“title”];
echo “<option> $categoryname </option>”;
}
?>
[/CODE]

to post a comment
PHP

10 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMar 21.2019 — It's just one of several output options in that case. Anything not within &lt;?php...?&gt; tags gets directly output to the browser; and PHP allows you to freely switch in and out of "PHP mode" as desired. In that specific case, I'd probably opt for your suggested style as being cleaner and easier to read. I'd probably also avoid the (apparently) unnecessary variable assignments, and possibly leverage sprintf() so that I could escape any problematic characters in the data as:
<i>
</i>&lt;?php
// . . .
while($daterows = $stmt-&gt;fetch()) {
sprintf(
"&lt;option&gt;%s&lt;/option&gt;n",
htmlspecialchars($daterows['title'])
);
}

:)
Copy linkTweet thisAlerts:
@ginerjmMar 21.2019 — While nogdog presents a very viable alternate solution, I believe that what you think is a good way of doing it is Exactly how I would do it. Avoid PHP Tags At All Costs. Personally I use a single <?php tag in almost all of my scripts.
Copy linkTweet thisAlerts:
@coleioauthorMar 21.2019 — thanks for the posts guys, i apologise but i am a complete beginner and some of this technical stuff goes over my head. can you explain to me how sprintf() works, i see you didnt need to use an echo
Copy linkTweet thisAlerts:
@NogDogMar 21.2019 — @coleio#1602089

Best way to start to learn any PHP built-in function is via the official manual: https://php.net/sprintf :)
Copy linkTweet thisAlerts:
@ginerjmMar 22.2019 — I agree with Nogdog - the manual is the best place to learn. Despite some readers resistance to reading technical stuff.....

As for using sprint - I can safely say that in my 5 or so years of using php I have probably only used it 2-3 times. It has its uses but for outputting some literals and a couple of vars (as in your case) the simple echo statement is all you'll ever need. The thing to remember when building strings and trying to output them is that double quotes are needed to cause the value inside a php var to be displayed. If you use single quotes around a php var all you'll see is the var NAME. Try these two lines in a little test script (a teaching moment) and see what you get:
<i>
</i>$myvar = "My Var Value";
echo "Using double quotes: This is what myvar contains: $myvar&lt;br&gt;";
echo 'But with single quotes: This is what myvar contains: $myvar&lt;br&gt;';
Copy linkTweet thisAlerts:
@NogDogMar 22.2019 — In this case it might be a bit of overkill to use printf(), but I used it because I wanted to apply a function to the data before outputting it, and that can get messy if you end up having to do a lot of concatenation or separate echo commands. Imagine if you had several such substitutions in one line of output, whereas with printf() you can do:
<i>
</i>printf(
"&lt;p class='foo'&gt;Hello, %s, your total cost for %s will be $%.2f.&lt;/p&gt;n",
htmlspecialchars($user['first_name']),
htmlspecialchars($item['name']),
$item['price'] + (round($taxRate * $item['price'], 2)
);

...versus...
<i>
</i>echo "&lt;p class='foo'&gt;Hello, " . htmlspecialchars($user['first_name']) .
", your total cost for " . htmlspecialchars($item['name']) . " will be $" .
($item['price'] + (round($taxRate * $item['price'], 2))
;

I personally find the former easier to read and thus to maintain, but your mileage may vary.
Copy linkTweet thisAlerts:
@techbMar 23.2019 — I might have a bit of the opposite opinion. Closing php tags and using raw html is usually the way I would do it. Echoing the html as a string can get confusing with all the quotes, and if you would need to use any javascript, echoing it as a string is not pretty at all. In your example it'll be fine using echo for now, but as the page gets bigger and more lines, echoing all the html is overkill and just adds extra work.
Copy linkTweet thisAlerts:
@NogDogMar 23.2019 — @techb#1602137

Which, in my admittedly contrived example, might have some people doing:
<i>
</i>&lt;p class='foo'&gt;Hello, &lt;?php echo htmlspecialchars($user['first_name']); ?&gt;,
your total cost for &lt;?php echo htmlspecialchars($item['name']); ?&gt; will be $&lt;?php
echo ($item['price'] + (round($taxRate * $item['price'], 2));?&gt;&lt;/p&gt;

You can make that more readable by doing some initial conversions to simple variables:
<i>
</i>&lt;?php
$safe_first_name = htmlspecialchars($user['first_name']);
$safe_item_name = htmlspecialchars($item['name']);
$final_price = $item['price'] + (round($taxRate * $item['price'], 2);
?&gt;
&lt;p class='foo'&gt;Hello, &lt;?= $safe_first_name ?&gt;, your total cost for &lt;?= $safe_item_name ?&gt;
will be $&lt;?= $final_price ?&gt;.&lt;/p&gt;
&lt;!-- OR --&gt;
&lt;?php echo "&lt;p class='foo'&gt;Hello, $safe_first_name, your total cost for $safe_item_name
will be $$final_price.&lt;/p&gt;n";

But now you're doing 3 additional variable assignments solely for the purpose of making your HTML output cleaner. Not a big deal, just adds a bit of code bloat.

Ultimately I'm not claiming any of these techniques (and other options) are correct/best, just that it's generally ugly when you combine HTML and PHP no matter which way you do it, and the main goal should be to use whichever technique in a given situation you think will be easiest to read/modify for you or whoever else has to modify it a year or two from now, when you've forgotten what you were doing and why. Don't just slap a bunch of HTML and PHP together in any old way that works and be satisfied. :)

PS: [u][HEREDOC notation](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)[/u] in PHP can help with the problems of having quotes in the output, which often makes embedding of JavaScript within the output easier.
Copy linkTweet thisAlerts:
@ginerjmMar 23.2019 — As quickly pointed out by Nogdog - heredocs is the way to go for a bunch of raw html. But for JS code - one should NEVER be worrying about writing JS when one is trying to output html. JS has no business being in the midst of either Html or PHP. Write your JS code in separate modules and include it using PHP.

Funny how we have morphed from discussing the benefits of a plain echo vs. sprint.....
Copy linkTweet thisAlerts:
@rootMar 25.2019 — Don't forget the HEREDOC method...
$somevar = "Cheese";
$anothervar = "Toast";

echo &lt;&lt;&lt;HEREDOC
&lt;p&gt;This is an example of how you can use some alternate method
of making your $somevar on $anothervar&lt;/p&gt;

HEREDOC;
×

Success!

Help @coleio spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...