Home > Software engineering >  How can I embed php in html?
How can I embed php in html?

Time:03-07

I cannot embed PHP syntax on HTML. This is the code:

<a
 <?php 
    $id = $this->session->userdata('medic');   
    if ($this->session->userdata('medic') != null) {
      echo ' data-toggle="collapse" role="button" href="<?= base_url('host/Search/schedule/').$id; ?>"';
    } else {
      echo 'style="display: none;"';
    }
 ?>
</a>

above is wrong code, I cannot write href="" content like that. What is the correct way to write this code? Thank you in advance.

CodePudding user response:

To accomplish what you're trying to do, try something like this:

<a
 <?php 
    $id = $this->session->userdata('medic'); 
    $url = base_url('host/Search/schedule/').$id;  
    if ($this->session->userdata('medic') != null) {
      echo "class='btn btn-primary' data-toggle='collapse' role='button' href='$url'";
    } else {
      echo "style='display: none;'";
    }
 ?>
 >
</a>

You cannot use <?= tags within <?php tags.

I modified this to create a variable for the url instead of generating it inline. Then I inverted the use of single and double quotes to allow you to use the variable inline.

CodePudding user response:

Code below uses ternary operator for a cleaner code.

<a
 <?php 
    $url = base_url('host/Search/schedule/').$id; 
 
    $attributes = $this->session->userdata('medic') ? "class='btn btn-primary' data-toggle='collapse' role='button' href='".$url."'" : "style='display: none;'"; 

    echo $attributes;
 ?>
> 
</a>

CodePudding user response:

It will be easier to debug html syntax errors if you don't heavily rely on echo() to output html. Instead simply end the php with ?> when you need to compose relative long lines of html. Then you can use <?= wherever if you prefer.

For example:

if ($this->session->userdata('medic') != null) {
    
    $id = $this->session->userdata('medic');
    
    ?><a  data-toggle="collapse" role="button" href="<?= base_url('host/Search/schedule/').$id; ?>">Whatever text to show for button</a><?php // resume php
}
else {?><a style="display: none">This serves no purpose</a><?php
    // really this else serves no purpose because if you don't output it, it won't render anyway
}

Of note, purposely put your html right after (same line) your ?> so that no whitespace gets inserted before your html.

Same token, purposely resume your php with <?php right after your html ends, same line.

Also, as shown above, make it easier on your eyes by composing the whole <a>...</a> in the branch, since your code doesn't seem to need it split up like you had it.

These are just tips to getting the html parts in your code with reduced bugs on html syntax.

  •  Tags:  
  • php
  • Related