[英]Using mysql to pull database information into html tables inside PHP script
首先,我真的希望我不要因為這個問題而被打敗,但是我願意冒風險,以便指出正確的方向,這樣我才能學習。
我有一個.php腳本,在我的PHP腳本中,我編寫了連接MySQL數據庫的代碼。
這是問題:
我有一張桌子,可用於非常簡單地展示食品。 目前我有:
<table width="1024" border="0" cellpadding="10" cellspacing="5" align="center">
<tr>
<td colspan="2"><font>Item Name</font></td>
<td colspan="2"><font>Item Name</font></td>
<td colspan="2"><font>Item Name</font></td>
</tr>
它繼續與其他表行元素...
它在哪里說“項目名稱”,我如何輸入代碼來提取數據庫信息。 我擁有的數據庫名稱是“TEST”,我希望每個項目名稱列出“ITEM”表中的不同項目。
任何幫助都會受到贊賞。
你真的需要對此進行更多的研究。 這是一個Php代碼示例,它從w3學校提供的數據庫中提取數據。 請參見http://www.w3schools.com/php/php_mysql_select.asp 。
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
您必須迭代數據庫中的結果,否則您將只能訪問第一行(或數組指針所在的位置)。
您的問題是編程的基礎知識,網絡上有關於此主題的數百萬資源。 我只會給你一個小樣本代碼,從這里開始調試和修改你的口味。
//Connect to MySQL Database
$connection = mysql_connect('host', 'user', 'password') or die("Connection error. Details: ".mysql_error());
//Select the database
$db_select = mysql_select_db('dbname', $connection);
//Create the query
$query = mysql_query("SELECT * FROM `foods`") or die("Error in query. Details: ".mysql_error());
//Check if the query has results, and iterate over it
if (mysql_num_rows($query) > 0)
{
//Creates the table
echo '<table>';
//Iterate over the MySQL results and print the data
while ($result = mysql_fetch_assoc($query))
{
echo '
<tr>
<td>'.$result['item_name'].'</td>
</tr>
';
}
echo '</table>';
}
else
{
echo "Your query hasn't returned results";
}
試試這個,不要忘記更改mysql主機名,用戶名,密碼,數據庫名稱和表名。
問候。
嘗試這個:
$conn = mysql_connect('host', 'user', 'password') or die("Connection error. Details:".mysql_error());
$db_select = mysql_select_db('<your_db_name', $conn);
$sql = mysql_query("SELECT * FROM `foods`")
if($sql)
{
echo '<table>';
while ($result = mysql_fetch_assoc($query))
{
echo '<tr><td>'.$result['<field_name1>'].'</td>';
echo '<td>'.$result['<field_name2>'].'</td>';
.....
.....
echo '</tr>';
}
echo '</table>';
}
else
{
echo "no results is there";
}
注意:您應該知道您的表列名稱,在field_names中提供相同的名稱,您可以打印表中存在的任意數量的列。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.