Sam
Sam

Reputation: 2347

Wondering the correct way to embed php in html

I wrote code to dynamically create a list of countries for a menu in HTML, and the code works when run as a php file, but when I tried to embed it in an html page, it didn't work.

My code looked something like

...

<form action=...>

<?php

include("connect.php");

$ret = mysql_query("SELECT * FROM countries");

echo "<select id='countries' name='countries'>";

while($array = mysql_fetch_array($ret)){

echo "<option value='{$array['abbrevs']}'>{$array['full']}</option>";

}

echo "</select>";

?>

</form>

with this, it output the while loop and php characters, but none of the html.

Upvotes: 1

Views: 277

Answers (4)

Trott
Trott

Reputation: 70055

Typically, a web server will be configured to treat files with a .php extension as PHP files but to treat files with a .html extension as plain HTML.

If you want to change that behavior and make it so files that have a .html extension are treated as PHP, you can use Apache's ForceType directive (assuming you're running Apache). Personally, I don't recommend doing that, but it certainly can be done.

Upvotes: 0

favoretti
favoretti

Reputation: 30167

You can embed the code in a .php or .phtml file, depending on your web-server configuration. .html files will be rendered with content-type text/html and therefore will be treated as such, without passing it through mod_php.

Upvotes: 0

alex
alex

Reputation: 490133

Give the file the php extension.

Generally, servers are set up to only run files with the php extension through PHP. You can modify this, but it is generally best to leave it.

Upvotes: 2

Brian Fisher
Brian Fisher

Reputation: 23989

Generally, you can't embed php code in an html file and have it interpreted as PHP. You should probably just name the file with the above code file.php instead of file.html.

Upvotes: 0

Related Questions