Can HTML be embedded inside PHP "if" statement? - php

I would like to embed HTML inside a PHP if statement, if it's even possible, because I'm thinking the HTML would appear before the PHP if statement is executed.
I'm trying to access a table in a database. I created a pulldown menu in HTML that lists all the tables in the database and once I select the table from the pulldown, I hit the submit button.
I use the isset function to see if the submit button has been pressed and run a loop in PHP to display the contents of the table in the database. So at this point I have the complete table but I want to run some more queries on this table. Hence the reason I'm trying to execute more HTML inside the if statement. Ultimately, I'm trying to either update (1 or more contents in a row or multiple rows) or delete (1 or more rows) contents in the table. What I'm trying to do is create another pulldown that corresponded to a column in a table to make the table search easier and radio buttons that correspond to whether I'd like to update or delete contents in the table.

<?php if($condition) : ?>
This will only display if $condition is true
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
This will only display if $condition is true
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.

Yes,
<?php if ( $my_name == "someguy" ) { ?>
HTML GOES HERE
<?php } ?>

Yes.
<?php if ($my_name == 'someguy') { ?>
HTML_GOES_HERE
<?php } ?>

Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).
Better is to use heredoc syntax. It is the same concept as in other languages (like bash).
<?php
if ($condition) {
echo <<< END_OF_TEXT
<b>lots of html</b> <i>$variable</i>
lots of text...
many lines possible, with any indentation, until the closing delimiter...
END_OF_TEXT;
}
?>
END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.
Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).
Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.

So if condition equals the value you want then the php document will run "include"
and include will add that document to the current window
for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`

<?php if ($my_name == 'aboutme') { ?>
HTML_GOES_HERE
<?php } ?>

I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.

Related

PHP four levels of quotes

Is there any possible way to have four levels of quotes? Or a more efficient way to print javascript using PHP?
Here is the context for why I need four levels of quotes:
The first level is required to wrap around script to echo.
<?php echo '<script></script>';
The second level is required to wrap around html to print in java
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button>test</button>\'</script>';
The third level is to wrap around onclick function in button
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button onclick="some_function()">test</button>\'</script>';
The fourth level is to wrap around the parameters in the function
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button onclick="some_function(*insert quote*parameter*insert quote*)">test</button>\'</script>';
Edit 1:
The entire script needs to be in echoed by php because in some scenarios the entire scripts needs to exist and other scenarios it needs to not exist e.g.
<?php if($variable == "do_not_print"){// do nothing}else{//echo script}
You can avoid string quoting problems by dropping out of the PHP context entirely and using
<?= ... ?>
to insert server-side values into the output.
json_encode() also helps sanitise values for safe use in a JavaScript context.
I also recommend using the DOM library for creating and inserting elements
For example
if ($someThingOrOther) :
// end PHP context
?>
<script>
(() => { // IIFE to avoid polluting the global scope
const someValueFromPhp = <?= json_encode($someValue) ?>
const button = document.createElement('button')
button.textContent = 'test'
button.addEventListener('click', () => {
some_function(someValueFromPhp)
}, false)
const box = document.getElementById('box')
// empty out "box", faster than using "innerHTML"
while(box.firstChild) {
box.removeChild(box.firstChild)
}
box.appendChild(button)
})()
</script>
<?php
// and now back to PHP
else:
?>
<script>
// ...
</script>
<?php
endif;
quote 1: ''
quote 2: ""
quote 3: \'\'
quote 4: \"\"
like this:
<div id="root"></div>
<?php
echo '<script type="text/javascript">
document.getElementById("root").innerHTML = "<button onclick=\"alert(\'its work\')\">test</button>\n";
</script>';
?>

Trying to understand what's going on in this PHP code?

I program in other languages but my job involves reading PHP and I'm trying to understand part of this view page (we use MVC).
<?
foreach ($slides as $i => $slide) {
?>
<li class="yui3-carousel-element<?=$i > 0 ? ' hidden-node' : ''?>">
<?
Why is the loop surrounded by <? and ?> ? I thought those go on either end of the entire PHP script, but instead I'm seeing them scattered throughout the whole thing.
That ternary expression seems to just be floating....it's not being echo'ed or print'ed or concatenated to anything....not to mention it weirdly seems to be comparing the number 0 to something I can't make out....it's not a string...it's an li element with no closing tag?? In php?? I'm very confused.
<? ?> are called short tags in PHP. They indicate the start and end of PHP code. The ternary is also wrapped with the short tags. That ternary is actually appending something to the class depending on whether or not the current index of $slide is greater than 0. The li is HTML and it should be closed.
<? is used as an opening tag for php-code and ?> as a closing tag. PHP can be mixed with other languages like HTML as seen in your example.
Actually it is being echo'ed, that's what the =right after the <? does. It is nothing else than a short command for echo. The other thing with the ? and : is another short form. Written out the whole thing equals if($i > 0) echo ' hidden-node'; else echo '';.
So the code adds <li>-Elements for every slide and for every slide except the first one it adds the class 'hidden-node', which most likely hides all other elements except the first one when the code gets loaded.
The <? and ?> tags are short tags saying that PHP code is inside of them. When they are closed, it goes back to simply outputting HTML.
The <?=that you see on the line is simply a shorthand for <?php echo
Personally I would have probably left the tag open at the start, then do echo on the line in the loop. What is there is the equivalent to the following:
<?php
foreach ($slides as $i => $slide) {
$hiddenElement = $i > 0 ? ' hidden-node' : '';
echo '<li class="yui3-carousel-element'.$hiddenElement.'">';
The loop is surrounded by those because it's exiting PHP code and entering HTML code. For example, you can do: <?php /*code here blah blah*/ if (...) { ?> <div>ha</div> <?php } /*more code*/ ?>. In PHP, if you don't wrap stuff with <?php ?>, then it's executed as HTML code.
That statement with <?= is a shortcut to echo'ing. It literally says <?php echo (($i > 0) ? ' hidden-node' : '' ?>.
the <? and ?> is shorthand for the php tags.
after that is clear you can see that the
<li class="yui3-carousel-element<?=$i > 0 ? ' hidden-node' : ''?>">
part is checking if $i is greater than 0 and displaying the hidden-node when it is

Stacking PHP code?

I've done a project that now needs to be changed in order to display one div if a variable is in an array and a different div if it isn't in the array.
Normally I'd just do
<?php $quartermonths = array("February","May","August","November");
if (in_array($month,$quartermonths))
{echo "quarter code in here";}
else
{echo "nonquarter code in here";}
?>
and be on my merry way, however the code I've got already contains a load of html and php code already, which doesn't like encapsulated within another PHP block (as far as I'm aware?)
e.g.
<?php $quartermonths = array("February","May","August","November");
if (in_array($month,$quartermonths))
{echo "Quarter HTML CODE
<?php quarter phpcode ?>";}
else
{echo "Non-Quarter HTML CODE
<?php non-quarter phpcode ?>";}
?>
So my question is, what is the best way to tackle this? Is it simply to do a javascript hide div A when the variable is met and hide divB when the variable isn't met, or is there a better solution?
Thanks
<?php
if (in_array($month,$quartermonths))
{ ?>
Quarter HTML CODE
<?php quarter phpcode ?>
<?php } ?>
split your html code from php code like this.
It sounds like you just want to concatenate the value of quarter phpcode. Let's say it's a single function, quarter_phpcode(). You can just do this:
{ echo "Quarter HTML CODE" . quarter_phpcode(); }

Does it make a difference if I put a bunch code inside a single php tag vs breaking it up?

Besides personal preference, does it make any difference?
<?php
$meta = get_post_meta(get_the_ID(), 'rw_strNum', true);
'' != $meta and print "$meta";
?>
<?php
$meta = get_post_meta(get_the_ID(), 'rw_strName', true);
'' != $meta and print "$meta";
?>
as opposed to this
<?php
$meta = get_post_meta(get_the_ID(), 'rw_strNum', true);
'' != $meta and print "$meta";
$meta = get_post_meta(get_the_ID(), 'rw_strName', true);
'' != $meta and print "$meta";
?>
The first version will output an extra newline character into the generated output, since there's one between the ?> and the <?php:
?>
<?php
That is the only difference; there isn't any noticeable performance impact between the two.
Everything outside <?php ?> is treated as output. This means, that
?>
<?php
may output something. "May" because the newline after ?> is part of the tag and therefore not returned. But with something like
?>
<?php
there are two whitespace echoed. The problem is, that you cannot set any headers anymore, after something is returned to the browser.
Like knittl said, it will not make any visible difference. The only difference is it will make your HTML easier to read when you mix PHP and HTML together, for example when doing templates.
The php parser goes through the whole file regardless and I doubt encountering a closing tag and then an opening tag has any impact on parsing/speed of parsing.
Yes it makes a difference. Look at this:
<?php
$uselessvar = 1;
?>
<?php
header('Location: /'); // This will not work
?>
<?php
$uselessvar = 1;
header('Location: /'); // This will work
?>
In the first example, there is a new line between the first closing tag ?> and the second opening tag <?php. This new line is treated as an output and it's send to the client. header function could not work if any output is sent to the client before its called. That's why the first example will not work where the second will.
In a more general way, it's better to use the closing tag ?> only where you need it, to avoid such errors.
For example, you don't have to put a closing tag ?> at the end of a php file. Sometimes we see a file terminated by a closing tag then a new empty line. This new empty line has the same effect as above, and can crash/alter any script.

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories