我是PHP的初学者。我想使用PHP和HTML页面从MySQL数据库中选择和显示数据。
我希望将PHP和HTML文件分开,因为我将使用jQuery Mobile和Phonegap,而Phonegap不支持PHP文件,因此我必须将PHP文件放在网络服务器中。 / p>
我已经尝试过寻找一个教程,但实际上互联网上的每个教程都展示了如何在一个PHP页面中完成所有这些教程。
这是我的代码,它工作正常,但它在一个.PHP文件中:
<html>
<head>
<title> Display Data </title>
</head>
<body>
<table border=1 cellpadding=1 cellspacing=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Email </th>
</tr>
<?php
//Create Connection with MySQL Database
$con = mysqli_connect('localhost','root','12345');
//Select Database
if(!mysqli_select_db($con,'profiles'))
{
echo "Database Not Selected";
}
//Select Query
$sql = "SELECT * FROM users";
//Execute the SQL query
$records = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($records))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Email']."</td>";
}
?>
</table>
</body>
</html>
提前感谢您的时间。
答案 0 :(得分:3)
你可以尝试这些方法。请记住,getemployees.php文件必须以一种格式生成输出,该格式可以直接在div中注入,看起来就像是一个表格。否则,您可以依赖JSON响应,然后遍历JSON数据记录并在客户端生成输出。
HTML文件:
<html>
<head>
<title> Display Data </title>
<script>
function getEmployees() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getemployees.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="txtHint"></div>
<script>getEmployees();</script>
</body>
</html>
PHP文件:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
//Create Connection with MySQL Database
$con = mysqli_connect('localhost','root','12345');
//Select Database
if(!mysqli_select_db($con,'profiles'))
{
echo "Database Not Selected";
}
//Select Query
$sql = "SELECT * FROM users";
//Execute the SQL query
$records = mysqli_query($con,$sql);
echo "<table border=1 cellpadding=1 cellspacing=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Email </th>
</tr>";
while($row = mysqli_fetch_array($records)) {
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>