Setting a CSS element class in PHP - php

I'm trying to modify a bit of PHP code to get it to assign a unique CSS class to the elements it creates as it cycles through its loop. Theoretically, I'm just trying to take a "name" that's echoed to the screen and assign that as a class to a element that's created next... Here's the intitial relevant code loop:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Simplistcally, I'm trying to get the string that's echoed by $exam->name to be assigned to the class of that <tr> element. Something like
<tr class="<?php echo $exam->name;"><td><?php echo $exam->name;?></td></tr>
Although I'm sure I'm handling the quotes or syntax improperly (at least, anyway, it doesn't end up assigning the class to the <tr>.

It will help if you stop going in and out of PHP so much, it will probably be easier to read this way:
<?php
foreach($my_exams as $exam){
if($exam->is_taken){
echo '<tr class="'.$exam->name.'"><td>'.$exam->name.'</td></tr>';
}
}
If you want to do double quotes, you need to escape them when you want to echo them, but then you can use a variable without concatenating a bunch of strings. (Once you are using objects/arrays it helps to surround each variable with {})
echo "<tr class=\"{$exam->name}\"><td>{$exam->name}</td></tr>";
Reference: http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

<tr class="<? echo $exam->name ?>"><td><? echo $exam->name ?></td></tr>

Others have answered this pretty much the same way I am about to, but I want to add this to explain the issue. And why this is not a “stupid” question, but more of a bizarre byproduct of the way that some CMS system mix HTML & PHP within their templates. In short: They format the template as nice HTML to make it seem clean & easy for non-coders, but in doing so their mixing of inline-PHP makes PHP coding seem more difficult than it is. Meaning this code:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Can easily be this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo '<tr><td>'
. $exam->name
. '</td></tr>'
;
}
}
?>
Which is now easier to parse from a programming standpoint, so you can now do this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo sprintf('<tr%s><td>', ' class="' . $exam->name . '"')
. $exam->name
. '</td></tr>'
;
}
}
?>
What I did there is use sprintf to place ' class="' . $exam->name . '"' into the ''. The %s means that is a string that should be placed there, and the string is what comes after the comma in the sprintf statement. I find this much easier to code, test & debug. But in general, the key to making PHP coding easier is to just use straight PHP when any logic needs to be placed in the context of HTML.

Related

Using Meta Box Plugin to assign URL to a variable

I'm a little lost here, hoping that someone can help. I'm using the Meta Box plugin for WordPress, and I'm trying to create a process for the user to select an option from a predefined list, and then assign a URL to that option as a link. Im trying to define the URL in a variable, and then call it in a function, but I'm still a little green on PHP syntax. this is my code now:
<?php
$article_url= rwmb_meta('orion_2016_article_url', 'type=URL');
if (rwmb_meta('orion_2016_article_source') != '') {
echo '<a href= ("$article_url") target=blank>';
echo rwmb_meta('orion_2016_article_source');
echo '</a>';} ?> on <?php the_date(); ?>
Since the options are already predefined, it seems like assigning a random URL to one of the options should be pretty simple. Hopefully this makes sense!
You need to to place variables you wish to echo inside double quotes or simply concatenate strings using . as in my example. Note that I didn't check the plugin's specific syntax, only general PHP syntax.
<?php
$article_url= rwmb_meta( 'orion_2016_article_url', 'type=URL' );
if (rwmb_meta('orion_2016_article_source') != '') {
echo '' . rwmb_meta( 'orion_2016_article_source' ); . '';
} ?> on <?php the_date(); ?>

PHP - Echoing a variable in color

Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.
My code without colour:
<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?>
I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?
The code I tried but doesn't work:
echo "<div style=\"color: red;\">fgets($file)</div>";
(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.
echo "<div style=\"color: red;\">" . fgets($file) . "</div>";
String Operators
Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.
Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
You should try:
<div style="color: red;"><?= fgets($file);?></div>
Note: <?= is an short hand method for <?php echo fgets($file);?>
This version does not need to escape double quotes:
echo '<div style="color:red;">' . fgets($file) . '</div>';
You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:
echo sprintf("<div style='color: red;'>%s</div>", fgets($file));
This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:
echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));

HTML code within PHP function

I have html code within a php function and it is displaying everything I need. I however find it very difficult to understand the use of . and ' when splitting up the code. I wish to change the layout to put the values within a table but struggle to get the correct syntax. Currently it looks like this;
$sub = $get_row['price']*$value; // Creates Subtotal of product
echo $get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £ '.number_format($sub, 2).'
[-]
[+]
[Delete]<br/>';
Is there a good tutorial/example about how to easily style this? Can anyone guide me in how this should be styled?
I am looking to put it in the following;
<table>
<th>Name</th>
<th>Price</th>
<th>Subtotal</th>
.....
What I think you are looking for is something like this
while($row - mysqli_fetch_array($here is your query)){
$id = $row["id"];
$name = $row["name"];
$html .='
[-]
[+]
[Delete]<br/>';
}
?>
<html>
<?php echo $html;?>
In this it loops through your query and for each ID it finds it creates your links and appends it to the $html variable. Then when you echo they will display in order.
If you don't mind using quoteless keys (see Accessing arrays whitout quoting the key), I find that putting your variables inside of double quotes when possible makes the entire string more readable and reduces the amount of concatenation you need to do.
echo "$get_row[name] x $value # £".number_format($get_row['price'], 2)." = £ ".number_format($sub, 2);
If you want that even more readable, store the number_format calculations in variables first.
Also, for big strings of html, I like to close out php and use tags to echo the variables, because it's more readable to me (I prefer short echo tags (<?= ?>), but it's officially not encouraged so I can't officially recommend it here ;) ).
?>
[-]
[+]
[Delete]<br/>
<?

using ' and " in php syntax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get useful error messages in PHP?
Ive started on part of my new year resolution and decided to learn php, as part of it im trying to parse in an xml feed, and echo out the name of the events wrapped in <a> tags linking them back to the events page on the xml feed's site.
I think ive got it all in but i cant seem to see why this isnt working im just getting a blank page, if some one could point me in the right direction it would be much appreciated, cheers
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href="$event_attributes['url']">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
</ul>
echo "<a href="$event_attributes['url']">";
try changing that line to
echo "<a href=\"".$event_attributes['url']."\">";
The Php parser is pretty funny about this. Usually you pick one and just stick to it, or use both single quotes and double quotes as you please. Just remember that strings with double quotes are parsed for variables.
$hello = "Hello";
echo "$hello master";
is the same as
$hello ="Hello";
echo $hello.' master';
When you are testing your PHP scripts, you'll find it useful to switch on errors - then PHP will actually tell you why it isn't showing you anything:
error_reporting(E_ALL);
Normally you will have missed a ; or mis-typed a variable name.
in your case the error is here:
echo "<a href="$event_attributes['url']">";
You have accidentally ended the string with a double quote, so PHP thinks the string ends here:
echo "<a href="
This is where using single-quotes can be very handy because your double quotes won't then close the string.
echo '<a href="' . $event_attributes['url'] . '">';
The main difference between single and double quotes in PHP is that double quotes has special clever parsing rules and single quotes doesn't. For example:
$myVar = "BLAH";
echo "Example $myVar"; // Example BLAH
echo 'Example $myVar'; // Example $myVar
In your unordered list, you should use a dot to concatenate your string, and escape your double quotes like this:
echo "<a href=\"".$event_attributes['url']."\">";
Instead of
echo "<a href="$event_attributes['url']">";
Your example throws and error because you haven't used proper string concatenation. However, even with correct concat, it would render as <a href=http://someurl>, and you'd need to add the double quotes according to html standard. Hence you have to double quote.
if you want to not be troubled by having to switch between using a ' or a " then i suggest using the php alternative syntax php alternative syntax
with the given code it would look like
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php foreach($type->market as $event):?>
<li>
<a href="<?php echo $event_attributes['url']; ?>">
<?php echo $event_attributes['name']; ?>
</a>
</li>
<? endforeach;?>
</ul>
one advantage this would bring is that it would produce cleaner code since you can clearly distiguish your php code from your html which is the presentational part at the price writing all those other <?php ?> and as what others would claim a performance degradation. the choice is yours
Change
echo "<a href="$event_attributes['url']">";
for
echo "<a href=".$event_attributes['url'].">";
You are missing the periods in your second echo, where you have your $event_attributes['url']
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href=".$event_attributes['url'].">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
I would recommend you to enable your error log, it would allow you to know the line with problems in any of your scripts.

best way of printing data

for example i want to generate html code, using some data from database.
here is two ways of printing data
<? echo '<li><img src="'.$row['image'].'" /></li>';?>
or
<? echo "<li><img src='$row[image]' /></li>";?>
both of them are working. and if so, why people use the first method, if without spliting the row by . it works fine too.
thanks
The best way would be to use only one method.
I'd even use <?php echo '<li><img src="' . $row['image'] . '" /></li>'; ?>
There's a speed difference, but that would be barely measurable and usually not at all noticable. Every string in double quotes is parsed first. That's why it's better to not use double quotes for strings at all. If you use extremely many strings with vars in it, it could become a measurable difference - but doing that would be quite bad design in the first place.
Btw.: The same is true for often switching the parser on and off with <?php and ?>.
The main reason for doing the above is good coding practice.
Others may need to understand your script too. And maybe yourself too some years later.
Vars in strings can be easier overlooked than vars included like this.
Even more so on IDEs with syntax highlighting.
I've even seen people put a newline before every var inserted in this way. But IMHO that's a little too much. ;)
More or less offtopic: No I didn't read all the fighting going on in the other answers, but I know the old "no it's not slower" vs. 'Yes it is' kindergarden by heart. ;)
For christs sake, you're coders, damnit. Just test it:
<?php
$startt = microtime(true);
for ($i = 0; $i <= 10000000; $i++) {
$test = 'This is test number ' . $i;
// $test = "This is test number " . $i;
// $test = "This is test number $i";
}
$endt = microtime(true);
echo 'Used time: ' . ($endt - $startt);
?>
For me the first one gave 5.1321198940277, the second one 5.2075009346008 and the third one 6.4821639060974 (more than 1.2 secs difference). Q.E.D. so far.
The interesting thing would be to try that on different systems. Maybe I'll make my own question for this.
echo sprintf('<li><img src="%s" /></li>', $row['image']);
Much easier to read and less prone to errors if it get's changed/extended later.
Another method:
<li><img src="<?php echo($row['image']); ?>" /></li>
<? echo '<li><img src="'.$row['image'].'" /></li>';?>
A reasonable strategy is to output all static content in plain PHP templating. That way you don't have to worry about PHP string literal escaping in the static content:
<li><img src="<? echo $row['image']; ?>"/></li>
However, (a) you need to use htmlspecialchars() on all raw-text strings output into HTML, or you've got potential cross-site-scripting issues. Also, <? short tags should generally be avoided as they may not be enabled on all servers.
To cut down on the amount of typing “htmlspecialchars” in templates, define a shortcut function:
<?php
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<li><img src="<?php h($row['image']); ?>"/></li>
In the second method:
<? echo "<li><img src='$row[image]' /></li>";?>
you cannot use functions, you can only use variables. It does not matter which method you use if you are printing variables.
the fastest way is to call the echo function with multiple parameters instead of a string that contains the concatenated parameters:
echo '<li><img src="',$row['image'],'" /></li>';
is the equivalent of
echo '<li><img src="';
echo $row['image'];
echo '" /></li>'
which is faster than
echo '<li><img src=";'.$row['image'].'" /></li>';
If you are using ' in your html tags for specifying attribute values then use " in PHP and if you are using " in html then use '. Either way you won't need to escape the quote in html by \

Categories