我在将MySQL数据库表打印到PHP代码时遇到问题。我希望MySQL表作为实际表格打印在我的网站上,而不仅仅是数据库值。我所做的一切似乎都不起作用,我已经看过类似的问题,但仍无法使其发挥作用。
答案 0 :(得分:0)
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
echo "</table>";
答案 1 :(得分:0)
您必须使用SELECT语句,以便从数据库中检索数据并将其保存在变量中。获得数据后,可以使用for循环打印表格。
答案 2 :(得分:0)
在你的html表单中放置一个名为fetch的提交按钮,如下所示
<form method="post" action="yourphpfilename.php">
<input type="submit" name ="fetch" value="FETCH DATA" />
</form>
并在您的php代码中插入此代码并进行配置。
if(isset($_POST['fetch']))
{
// Connect to database server
$con=mysqli_connect("localhost", "root", "") or die (mysqli_error ());
// Select database
mysqli_select_db($con,"databasename") or die(mysqli_error());
// SQL query
$strSQL = "SELECT * FROM tablename ;
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($con,$strSQL);
print "
<table border=\"5\" cellpadding=\"5\" cellspacing=\"0\" style=\"border- collapse: collapse\" bordercolor=\"#808080\" width=\"100%\" id=\"AutoNumber2\" bgcolor=\"#C0C0C0\">
<tr>
<td width=100>ID:</td>
<td width=100>First Name</td>
<td width=100>Last Name</td>
<td width=100>Email</td>
<td width=100>User Name</td>
<td width=100>Password</td>
<td width=100>Date Of Birth</td>
<td width=100>Gender</td>
</tr>";
while($row = mysqli_fetch_array($rs))
{
print "<tr>";
print "<td>" . $row['id'] . "</td>";
print "<td>" . $row['fname'] . "</td>";
print "<td>" . $row['lname'] . "</td>";
print "<td>" . $row['Email'] . "</td>";
print "<td>" . $row['uname'] . "</td>";
print "<td>" . $row['password'] . "</td>";
print "<td>" . $row['dob'] . "</td>";
print "<td>" . $row['gender'] . "</td>";
print "</tr>";
}
print "</table>";
}
}
答案 3 :(得分:-1)
试试这个:
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>