[英]How to get mysql column names and the values
我正在嘗試動態獲取列名和值,這意味着是否要在數據庫中添加新列時要在刷新頁面時在前端顯示
下面將為我提供列名,但隨后我需要檢索與列名有關的值。有人可以指導我如何做到這一點。
<?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>";
?>
可以執行以下操作:(只要您檢索列名的功能正常工作)
編輯代碼
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_函數。
正如@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());
}
嗨,請使用此代碼-
$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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.