2

我正在尝试动态获取列名和值,这意味着如果在数据库中添加了新列,我想在页面刷新时显示在前端

下面将为我提供列名,但随后我需要检索与列名有关的值。谁能指导我如何做到这一点,谢谢。

  <?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>";

    ?>
4

3 回答 3

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_ 函数。

于 2013-10-06T08:11:07.850 回答
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());
}
于 2013-10-06T09:24:02.757 回答
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++;
}
于 2014-07-10T14:18:19.357 回答