Reputation: 35
I am using HTML
as my base and my file is called index.php
- I have a secondary .php
page called PHPSyntax.php
that holds php
functions in it. How from within index.php
can I call a function from phpsyntax.php
and return the result to index.html
File structure is like this: Index.php
<html>
<body>
<h4>PHP Testing</h4>
<form>
<select>
<option value="null" selected="selected"></option>
//here is where I want to call and return the values from my php
</form>
</body>
</html>
And my PHPSyntax.php
reads like this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "Select name As 'employeename' from employees";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) { echo "<option value=".$row['employeename'].">".$row['employeename']."</option><br>"; }
}
else echo "<option value='null'>default</option>";
$conn->close();
?>
Upvotes: 1
Views: 2412
Reputation: 470
<?php
/*PHPSyntax.php Is not work because you have to change index.html for index.php. So, once you do that, you have to do everything in the same file unless you make functions into the your extra file that connect with your database.
Method One. Do it with two separate files and make a function for display your option trough php. How? See this.*/
function get_options() {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "Select name As 'employeename' from employees";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$option = "<option value=".$row['employeename'].">".$row['employeename']."</option><br>";
return $option;
}
}
else $option = "<option value='null'>default</option>"; return $option;
$conn->close();
} //Once you already make a function, in your index.php require the file PHPSyntax.php like
?>
<form>
<select>
<option value="null" selected="selected"></option>
<?php echo get_options(); ?>
</form>
Upvotes: 0
Reputation: 15489
I might be missing something - but why can't you leave the index.html as your main page and do an Ajax call to the .php page on page load and append the returned content into the desired location using the success function of hte Ajax call. That way you keep the .html extension, you set the form elements dynamically (and it appears that all you are doing is setting the employees names into the select list) and all is good in the world.
Upvotes: 0
Reputation: 9782
Change the name of index.html to index.php and include the .php code like so:
<?php require_once 'PHPSyntax.php' ?>
Upvotes: 2