gpt4 book ai didi

php - 如何从mysql中提取列名和php中的条目,列名只显示一次

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

我正在尝试从 php 中的 mysql 中提取一个表,其中列名用作标题,列中的值显示为值。

| id | firstname | lastname ||  1 | Joe       | Jones    ||  2 | Cal       | Clark    ||  3 | Rob       | Robin    |

problem is i am getting back

| id | firstname | lastname ||  1 | Joe       | Jones    || id | firstname | lastname ||  2 | Cal       | Clark    || id | firstname | lastname ||  3 | Rob       | Robin    |

please help with what i am doing wrong.

P.S I am quite new to programming also don't mind the poor html.

$query = "SELECT * ";
$query .= "FROM {$selected_table} ";
$query .= "LIMIT 0, 30";

$confirmed_query = confirm_query($query);
$query = mysql_query($confirmed_query);

echo "<table>";
while ($query_result = mysql_fetch_assoc($query)) {
echo "<tr>";
foreach ($query_result as $columns => $rows) {
echo "<th>{$columns}</th>";
}
echo "</tr><tr>";
foreach ($query_result as $colums => $rows) {
echo "<td>$rows</td>";
}
echo "</tr>";

}
echo "</table>";

有没有其他方法可以在不使用 foreach 的情况下从数组中获取列名,这将导致它返回数组中每条记录的列名?

最佳答案

这是 do...while 的工作!

$query_result = mysql_fetch_assoc($query);
if ($query_result) {
echo "<table>";
echo "<tr>";
foreach ($query_result as $columns => $rows) {
echo "<th>{$columns}</th>";
}
echo "</tr>";
do {
echo "<tr>";
foreach ($query_result as $colums => $rows) {
echo "<td>$rows</td>";
}
echo "</tr>";
} while ($query_result = mysql_fetch_assoc($query));
echo "</table>";
}

但我也给@outis 的回答 +1,因为我们都应该使用 PDO —— 而不是过时的和劣质的 mysql 扩展。

关于php - 如何从mysql中提取列名和php中的条目,列名只显示一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8422340/

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