gpt4 book ai didi

php - 从 SQL 数据库检索数据到 HTML 表

转载 作者:行者123 更新时间:2023-11-29 10:37:26 25 4
gpt4 key购买 nike

我正在尝试从数据库获取数据到 html 表。数据库中有一个公司表,其中包含 id、名称和百分比列。

以上表格中的数据是我手动输入的。我需要通过从数据库检索来填充相同的值。

数据库中的公司表如下所示。 Database table

在我的编码中,在数组形成的地方出现错误。我试图将所有名称放入一个数组中并在 html 表中打印。我恳请查看我的编码。高度赞赏。

$sql = "SELECT name, percentage FROM company";
$result = $conn->query($sql);

$result = $conn->query($sql);
if ($result->num_rows > 0) {

// output data of each row
while($row= $result->fetch_assoc()) {
$arr=str_split($row)

//echo $row;
echo "<table> <tr> <td> $arr[1] </td> </tr> </table> ";

}
} else {
echo "0 results";
}

@jakumi 错误是 enter image description here 。第 18 行是“$arr=str_split($row);”。

最佳答案

str_split 需要一个字符串,但 $row 已经是一个数组。例如,您只需通过 $row['name'] 访问每行的字段。

所以

echo '<table>';
while($row= $result->fetch_assoc()) {
echo '<tr><td>'.$arr['name'].'</td><td>'.$arr['percentage'].'</td></tr>';
}
echo '</table>';

更新以回答特定评论:

$percentages = [];
$namesToPercentages = [];
$collection = [];
while($row = $result->fetch_assoc()) {
$percentages[] = $row['percentage'];
// this produces [0 => 0, 1=>1.1, 2=>1.2, ...]

$namesToPercentages[$row['name']] = $row['percentage'];
// this produces ['Base_price' => 0, 'A' => 1.1, ...]

$collection[]= $row;
// this produces [['name' => 'Base_price', 'percentage'=>0], [...],...]
}

关于php - 从 SQL 数据库检索数据到 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46169233/

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