我使用HTML
作为我的基础,我的文件名为index.php
-我有一个称为PHPSyntax.php
的辅助.php
页面,其中包含php
函数。如何在index.php
中从phpsyntax.php
调用函数并将结果返回给index.html
文件结构如下: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>
我的PHPSyntax.php
读起来像这个
<?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();
?>
将index.html的名称更改为index.php,并包含类似的.php代码:
<?php require_once 'PHPSyntax.php' ?>
我可能遗漏了一些东西,但为什么不能将index.html作为主页面,在页面加载时对.php页面进行Ajax调用,并使用hte Ajax调用的成功函数将返回的内容附加到所需位置。通过这种方式,您可以保留.html扩展名,动态设置表单元素(看起来您所做的只是将员工姓名设置到选择列表中),这一切都很好。
<?php
/*PHPSyntax.php不起作用,因为您必须将index.html更改为index.php。所以,一旦你这样做了,你就必须在同一个文件中做所有事情除非将函数放入与数据库连接的额外文件中。
方法一。用两个单独的文件来完成,并通过php创建一个显示选项的函数。怎样见此。*/
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>