我正在尝试获取列名称和动态值,这意味着如果在数据库中添加了新列,我想在页面刷新时显示在前端
以下将为我提供列名,但我需要检索有关列名的值。任何人都会指导我如何做到这一点。
<?php
Include"db.php";
echo "<table>";
echo "<tr>";
$qColumnNames = mysql_query("SHOW COLUMNS FROM fullnames") or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
$colname = mysql_fetch_row($qColumnNames);
$col[$colname[0]] = $colname[0];
$x++;
}
foreach($col as $head){
echo "<th>$head</th>";
}
echo "</tr>";
echo "</table>";
?>
答案 0 :(得分:3)
可以执行以下操作:(前提是您的重命名列的名称正在运行)
已编辑的代码
Include("db.php");
echo "<table>";
$qColumnNames = mysql_query("SHOW COLUMNS FROM fullnames") or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
$colname = mysql_fetch_row($qColumnNames);
$col[$colname[0]] = $colname[0];
$x++;
}
$result = mysql_query("SELECT * FROM fullnames");
$counter = 0;
while($row = mysql_fetch_assoc($result)){
foreach($col as $c){
$rows[$counter][] = "<td>" . $row[$c] . "</td>";
}
$counter++;
}
echo "<tr>";
foreach($col as $c){
//echo headers
echo "<th>" . $c . "</th>";
}
echo "</tr>";
foreach($rows as $r){
//Echo all content
echo "<tr>";
foreach($r as $cell){
//echo all cells
echo $cell;
}
echo "</tr>";
}
echo "</table>";
?>
没有时间对此进行测试,但它应该有效。 (但你应该改用msqli_函数。
答案 1 :(得分:0)
@Toby Allen要求将我的评论格式化为答案:
...
// Just select absolutely all columns, including last two "dynamic" columns.
$query = $mysqli->query('SELECT * FROM fullnames') or die($mysqli->error);
// Get data and column names together
if ($row = $query->fetch_assoc()) {
$columns = array_keys($row);
// Do what you need with $columns
echo '<tr>';
foreach ($columns AS $column) {
echo '<th>' . htmlspecialchars($column) . '</th>';
}
echo '</tr>';
do {
// Do what you need with rows
echo '<tr>';
foreach ($row AS $column => $value) {
echo '<td>' . htmlspecialchars($value) . '</td>';
}
echo '</tr>';
} while ($row = $query->fetch_assoc());
}
答案 2 :(得分:0)
嗨请使用此代码 -
$query = 'select * from fulllnames WHERE id=1';
$result = mysql_query($query);
$i = 0;
$getResult=mysql_fetch_array($result, MYSQL_ASSOC);
while ($i < mysql_num_fields($result)){
$fld = mysql_fetch_field($result, $i);
$myarray=$fld->name;
//Field column name = Field value
echo $myarray.' = '.$getResult[$myarray]."<br>";
$i++;
}