问题描述
<?PHP
// establishing DB connection
if(isset($_POST['button']))
{
$text=$_POST['Database'];
}
$host = "host=localhost";
$port = "port=5432";
$dbname = "dbname=$text";
$dbuser = "user=postgres";
$dbpwd = "password=********";
// connection string
$dbconn = pg_connect("$host $port $dbname $dbuser $dbpwd");
// validating DB connection
if (!$dbconn)
{
echo 'Connessione fallita';
}
?>
用于填写上一个脚本的 $dbname 字段的 html 表单:
<html>
<body>
<form action="page.html" method="post" target="_blank">
<label for="Database">Database:</label>
<input type="text" id="Database" name="Database"><br><br>
<input type="submit" name="button" value="Submit">
</form>
</body>
</html>
查看表格的页面 HTML:
<html>
<head>
<Meta charset="utf-8">
<script src="js1.js"></script>
</head>
<body>
<div id="table1" class="table">
<table >
<thead>
<tr>
<th>Field1</th>
<th>Field2</th>
</tr>
</thead>
<tbody id="result">
</tbody>
</table>
</div>
</body>
</html>
用于生成表格的 js1.js 脚本:
$(function() {
$.getJSON("script.PHP",function(data) {
$.each(data,function(index,row) {
$("#result").append("<tr>");
var $tr = $("<tr>");
$.each(row,function(index2,column) {
$tr.append("<td>" + column + "</td>");
});
$("#result").append($tr);
});
});
});
<?PHP
// establishing
include('connect.PHP');
$query = 'SELECT... FROM...';
$result = pg_query($query) or die('Error message: ' . pg_last_error());
while ($row = pg_fetch_assoc($result)) {
$records[]=$row;
}
foreach( $records as $record )
$json[] = array($record['Name'],floatval($record['TempoMedio']) );
header("Content-Type: application/json");
echo json_encode($json);
?>
我认为生成表格的脚本存在问题,因为没有显示任何内容。 如果我不使用表单,而是直接在“connect.PHP”文件中写入数据库名称,则一切正常。
如何通过表单连接查看表上的数据?
解决方法
对 page.html
的 POST 请求与对 script.php
的 GET 请求不同的 HTTP 请求。
您没有将数据库名称发送到 script.php
(我假设它包含 connect.php
),而只是发送到 page.html
(这是一个 HTML 文档而不是 PHP 脚本,因此除非有一些不寻常的服务器配置设置在起作用,POST数据将被忽略)。