PHP echo adding functions - php

What I am trying to do is get an echo of the following php call and subtract 14.1% from the displayed number.
The code:
<?php echo $program->current_amount(); ?>
Can I add arithmetic functions to this in order to display the 14.1% deduction?

I think you're looking for a basic math operation in your output that has no effect on a database or anything else, correct?
If so, do something like the following:
<?php
// Set values
$current_amount = 100;
$pcnt_off = 14.1;
// Do the math
$out = $current_amount - ($pcnt_off/100) * $current_amount;
// Output
echo $out . " is " . $pcnt_off . "% off of " . $current_amount;
?>
http://codepad.org/RqF8cuvN
More specifically to your case:
<?php echo $program->current_amount() - 0.141 * $program->current_amount(); ?>

You can perform expressions inside an echo statement, yes; just wrap it in a (), so:
<?php echo ($program->current_amount() - .141); ?>
It may not even be necessary to use (). Incidentally, if your environment supports short tags, you can simply do:
<?= $program->current_amount() - .141 ?>
Keep in mind, though, that that code won't actually remove 14.1% from your number--you would want to multiply by .859.

Related

Run PHP code while echoing PHP

I'm using the echo command in PHP, but I want to enter PHP code like <?php echo $variable [id_login]?>, while echoing something else out, but this does not work.
Is this possible to do, and if so, how would I do it?
echo "<script>location='member.php?&id=<?php echo $taruh[id_login] ?></script>";
You cannot use echo or open/cloce php twice like you did, you might want to try something like the line below,
echo '<script>location=member.php?id=' . $taruh[id_login] . '</script>';
after echo you can write enything you'd like, even if it's a php variable, just use single quote and dot where you need it (like I do here), as you can see, echo is only used once..
For example:
<?php
$your_variable = 'some text';
$other_variable = 'some PHP code';
echo 'I wrote: ' . $your_variable . ' and ' . $other_variable . '!';
?>
Output will be:
I wrote: some text and some PHP code!
I hope this will bring you into the right direction..
EDIT
Also important: if you use query string in URLs, the first 1 can be a ? every other part after should be a & for example see the url below
http://www.example.com/index.php?id=12345&coder=yes&country=usa
before id I used a quest sign, for all others I didn't use the quest sign...

Using a php function inside a php echo

I'm trying to setup my WordPress website so that if a post / page has a featured image assigned, this image will be used as the page banner. If however the page doesn't have a featured image, it must onload select a random image out of six available options. I've tried to used this if statement below:
<div id="slider">
<div class="theslide">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
else {
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6); '.jpg">';
}
?>
</div>
</div>
It works, but the random number function is not closing preperly, so the code ends up looking like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6 </div>
</div>
</div>
Instead of like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6.jpg">
</div>
</div>
I'm assuming my syntax is wrong for using php inside of the echo, but everything I try either has the same problem or cause a php error.
Any help would be appreciated.
Thanks in advance
Willem
If you don't need to know which header was chosen, just do this:
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';
Using more than one ; on a line is a no-go (you are essentially telling the php-interpreter that '.jpg">'; is an independant command - which will do nothing)
Assigning a variable (ie. $whatever = 'something) inside the echo statement won't be a problem in this case - though it really doesn't do any good either. What it does is create a new variable called $random that you could use afterwards to find out which header was used - but results will be unpredictable if used in the echo statement (ie. in your case the variable would contain [random number].jpg, not just the random number), instead assign the random number to $random first like this:
$random = rand(1,6);
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random . '.jpg">';
echo "We are using header {$random}, which was chosen at random.";
Note that the above example also shows an alternate way to include the variable in a string - using double-quotes you can simply write the variable directly inside the string itself. When doing so I recommend always using {} to wrap the variable though not needed in this case - this allows referencing more complex variables (such as array elements or object properties), and it makes the whole thing more readable too.
Other (IMO less readable, possibly more error-prone) solutions include:
$random = rand(1,6);
echo "<img src=\"/wp-content/uploads/link-ship-chandlers-banner-$random.jpg\">";
echo sprintf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
printf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
Actually this can work, but you end the line with ;.
So removing the ; and adding a .
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6) . '.jpg">';
do this alternatively you don't need to set this variable
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';

Setting a CSS element class in 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.

Adding A Dynamic Link In Php

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

How can I retrieve HTML/PHP code stored in a mySQL table and not have the PHP commented out?

I am storing in a mySQL table the HTML/PHP content of individual slides to be displayed on a single page.
Here is an example of HTML/PHP code stored in the mySQL table:
<p>Welcome <?php echo $userData['fname']; ?>!</p>
<p>You made it to the first slide!</p>
I retrieve the content of the slides in PHP with the following code:
<?php
$fetchedPageSlideData = mysql_query("SELECT * FROM pageSlides WHERE pageID = $pageID ORDER BY 'order' DESC") or die(mysql_error());
while ($pageSlideData = mysql_fetch_array($fetchedPageSlideData)) {
$pageSlideContent = $pageSlideData['content']; ?>
<div><?php echo $pageSlideContent; ?></div>
<?php }
?>
All of the HTML of the content displays correctly, but the PHP is inserted as follows:
<!--?php echo $userData['fname']; ?-->
So the PHP is commented out and doesn't display.
How can I retrieve the HTML/PHP code and have the PHP not commented out?
It might be a better idea to use placeholder strings in the DB data. Executing arbitrary php code from a DB can be dangerous. PHP is Evil
Look into PHP function eval(): http://php.net/manual/en/function.eval.php
Dropping in and out of the PHP interpreter makes your code rather difficult to read. Consider:
<?php
$f = mysql_query(
"SELECT *
FROM pageSlides
WHERE pageID = $pageID
ORDER BY 'order' DESC"
) or die(mysql_error());
while ($d = mysql_fetch_array($f)) {
print "<div>" . $d['content'] . "</div>\n";
}
Regardless there is no implicit nor explicit mechanism here which would inject the comment tags you've presented. However it may be the browser trying to make sense of the unescaped html code and <?php ... ?> tags.
Try:
print "<div>" . htmlentities($d['content']) . "</div>\n";
As a side note, you might consider using
print "<div>" . highlight_string($d['content']) . "</div>\n";
Or do you mean that you actually want to run the code stored in the database - if so, you're asking for a world of pain. Eval is not evil - but you really must know what you're doing to avoid getting bitten by it.

Categories