我试图创建我的第一个网站,我在这种情况下无能为力。所以我有一个带表的MySQL数据库。我有一个名为database.php的php-File,它从数据库读取并回显查询的所有行:
<?php
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Name, Beschreibung, Datum, Uhrzeit FROM Termine";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Name"]. " - Beschreibung: " . $row["Beschreibung"]. " - Datum: " . $row["Datum"]. " - Uhrzeit: " . $row["Uhrzeit"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
现在在我的index.php上我想在调用/加载网页时执行这个php代码并打印所有行(数据条目)。但我不知道如何获取打印在我的网页正文中的php文件的echo(=数据条目)。我读到了关于AJAX和使用js脚本但我仍然无法弄明白。
谢谢你的帮助。
选项1:将PHP代码放在HTML正文中。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo 'Hello World';
// ...
?>
</body>
</html>
选项2:创建一个单独的PHP文件,其中包含上面的代码,并将/包含在您的身体中。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include_once('your_php_file.php');
?>
</body>
</html>
选项3:使用AJAX调用调用PHP文件(例如,使用jQuery load()
)。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="aDiv"></div>
<script> $( "#aDiv" ).load('your_php_file.php', function() { console.log('Loaded'); });</script>
</body>
</html>
如果索引文件是index.php,则在加载网页时将运行PHP代码。当然,这是假设您的Web服务器(本地或远程)已安装PHP。