Can HTML be embedded inside PHP "if" statement?


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.

3/7/2015 5:17:39 PM


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


<?  if($my_name == 'someguy') { ?>
<?  } ?>

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).

 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 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:


$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') { ?>
<?php } ?>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]