[英]Displaying SQL data in HTML form
我用PHP編寫了以下代碼,以從mysql表中獲取詳細信息,但我不知道如何以HTML形式顯示它們。
<?php
$servername = "localhost";
$username = "root";
$password = "icsk";
$dbname = "yusuf";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT dsl, Fname, Lname, Cid, pack FROM homereg";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['dsl']. " " . $row['Fname']. " " . $row['Lname']. " " . $row['cid']. " " . $row['pack'] ."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
上面的代碼借助echo將數據顯示在網頁上,但我希望它以表格形式顯示。 HTML表單具有以下代碼:
<form method="POST" name = "frm" action="homerenew.php">
<div align="center">
<table border="1" width="425">
<tr>
<td width="223"><font face="Georgia"><b>Subscription Number</b></font></td>
<td width="186"><input type="text" name="T1" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Your Current Pack</b></font></td>
<td width="186"><input type="text" name="T2" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Renewal Options</b></font></td>
<td width="186"><select size="1" name="D1">
<option value = "1 Month">1 Month</option>
<option value = "2 Months">6 Months</option>
<option value = "1 Year>1 Year</option>
</select></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Balance Payable</b></font></td>
<td width="186"><input type="text" name="T3" size="20"></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" value="Renew" name="B1">
<input type="reset" value="Reset" name="B2"></p>
</form>
我是PHP連接的新手,這就是為什么有點困惑的原因。 幫助將不勝感激。 謝謝
首先,您需要包含HTML表單的頁面的.php擴展名。
從數據庫中獲取數據后,您可以將其設置為表單元素,例如
<input type="text" name="T1" size="20" value="<?php echo $row['dsl'];?>">
我建議使用類似於PHPTal的模板引擎。 您將html頁面編寫為包含tal:標記的.xhtml文件,模板引擎使用該標記插入php值。 安裝說明 , 使用示例 。
使用模板引擎的好處是您可以從腳本中刪除所有html內容,並將顯示邏輯保留在xhtml文件中。 php代碼只是收集數據並將其分配給模板知道的標簽。
您可以將所有行作為數組獲取,並將其分配給php中的模板對象中的變量名稱。 然后在xhtml文件中使用該變量名來重復表(或任何其他元素)中的行。
Php:
<?php
require_once 'PHPTAL.php';
$rows = getMyDBRows();
// create a new template object
$template = new PHPTAL('my_template_file.xhtml');
$template->rows = $rows;
// execute the template
try {
echo $template->execute();
}
catch (Exception $e){
echo $e;
}
Xhtml行部分,其中包含重復每一行,插入元素內容,設置屬性以及使用條件語句僅顯示索引為1的行的輸入字段的示例。Repeat方法可用於selects中的選項和設置所選屬性的條件檢查。 Phptal要求嚴格的xhtml結構,如果您的xhtml中有任何錯誤,則該頁面將返回錯誤,指出出現問題的位置。
<tr tal:repeat="row rows">
<td tal:content="row/dsl"><\td>
<td tal:content="row/fname"><\td>
<td><input name="lname" tal:attributes="value row/lname, style php: repeat.row.id EQ 1?'display:inline-block':'display:none" tal:content="row/lname"></input>
......
<\tr>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.