gpt4 book ai didi

php - 使用 PHP 从数据库中提取的数据创建 html 表

转载 作者:行者123 更新时间:2023-11-29 07:28:02 24 4
gpt4 key购买 nike

我正在开发一个项目,通过 PHP 从 SQL 数据库中提取数据并从中创建 HTML 表。它是我正在创建的表单的一部分,该表将列出我所销售的商品、成本、重量等。无论如何,我需要使用 PHP 来完成此操作。到目前为止,我的代码的这一部分中有以下内容来制作此表:

<?php
$db=mysqli_connect(null,null,null,'weblab')
or die("Can't connect to DB: " .
mysqli_connect_error());

$query="SELECT fruit_item_no, fruit_name, fruit_price, fruit_weight FROM fruit_$

$result=mysqli_query($db, $query);
if (!$result) {
print "Error - The query could not be executed!" .
mysqli_error();
}
print "<table class = 'main'><caption> <h2> Fruit Purchasing Form </h2> </c$
print "<tr align = 'center'>";

$num_rows=mysqli_num_rows($result);

if ($num_rows > 0) {
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);

$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";

for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
}
else {
print "There were no such rows in the table <br />";
}
print "</table>";
?>

我遇到的问题是当我尝试在 Chrome 中查看整个页面时,我看到的只是:

PHP Error

我认为错误出现在这部分代码附近:

for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";

如果有人能给我一些关于我可能缺少的东西的指导,我将不胜感激。我已经研究了一段时间,但还没有找到明确的解决方案。

更新:我认为最好只更新我的帖子,而不是在某个地方提出新问题或评论。感谢您的所有建议,我能够更正我的代码以正确显示我的表格并解决所有验证错误。我为代码阅读噩梦道歉......我在这方面还很新,我需要在这方面付出更多努力。

我确实遇到了一个我仍然无法解决的问题。我试图在我创建的表中每行的末尾添加一个输入框。问题是,无论我尝试什么,这些框都会保持在表格上方的一行中(几乎位于浏览器屏幕的顶部。

我将这一行放在sql查询 block 中以尝试获取输入框:

echo ("<input name='item[]' type='text' .=''/>");

我也尝试过:

echo ("<input type='text' name ='item'/>");

两者都做了同样的事情,在顶部给了我一排盒子。您可以提供任何指导来让它们出现在每行的末尾吗?我不需要它将数据放回数据库或添加到那里的表中。我只是想获取允许输入与我的表单一起提交的输入字段。

最佳答案

您可以通过对结果运行 while 循环并迭代行来简化代码。然后使用 foreach 循环,因为每一行都是键值对的数组。在第一次迭代中,您可以打印标题。

$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$i = 0;
// loop through each row in the result
while ($row=mysqli_fetch_assoc($result)) {
// if first then print the header
if ($i == 0) {
print "<tr>";
foreach ($row as $field => $value) {
print "<th class='a'>".$field."</th>";
}
print "</tr>";
}
// print the row
print "<tr>";
foreach ($row as $value) {
print "<td class='b'>".$value."</td>";
}
print "</tr>";
$i++;
}
}
else {
print "<tr></td>There were no such rows in the table</td></tr>";
}

正如评论中所建议的,将 View 与代码分开是个好主意。

关于php - 使用 PHP 从数据库中提取的数据创建 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com