2

我想从特定表中获取所有列名和值。此表中的字段不是固定的,因此有时用户会添加一个字段,也可以将其删除。我想要做的是检索所有列名并获取它的值。就我现在而言,正在检索列名并从中获取一个值。我知道为什么我会得到这个结果,但我不知道如何解决它。

//I edited this sql, normally the table value and id are variable
$sql = "SELECT * FROM ".$_POST['moduleName']." WHERE modItemID= ".$_POST['modItemID']; 
$query = mysql_query($sql); 
$columns = mysql_num_fields($query); 
for($i = 1; $i < $columns; $i++) { 

//read field name
  $fieldName = mysql_field_name($query,$i);
  while($row = mysql_fetch_assoc($query,$i)){
    echo $fieldName."=".$row[$fieldName];   
  }

}  

结果:naam=Ketting

4

3 回答 3

7

实际上,解决您的问题的真正简单方法是使用 foreach 循环,如下所示:

while($row = mysql_fetch_assoc($query))
{
    foreach($row as $key => $value)
    {
        echo "$key=$value";
    }
}
于 2012-11-27T11:39:34.360 回答
5

mysql_fetch_assoc返回一个关联数组。您可以使用foreach循环来检索数组中每个项目的键=>值。

$sql = "SELECT * FROM products WHERE modItemID= 14"; 
$query = mysql_query($sql); 
$columns = mysql_num_fields($query); 
for($i = 1; $i < $columns; $i++) { 

//read field name
  $fieldName = mysql_field_name($query,$i);
  while($row = mysql_fetch_assoc($query,$i)){
    foreach($row as $column=>$value) {
      echo "$column = $value\n";
    }
    echo $fieldName."=".$row[$fieldName];   
  }

}  
于 2012-11-27T11:38:50.953 回答
0

只需输入您的数据库名称、用户名、密码和表名。

您从主数据库中获取所有数据(带有列名)

<?php 

function qry($q){

    global $qry;
    try {   
    $host = "?";
    $dbname = "?";
    $username = "?";
    $password = "?";
    $dbcon = new PDO("mysql:host=$host; 
    dbname=$dbname","$username","$password");
}
catch (Exception $e) {

    echo "ERROR ".$e->getMEssage();

}

    $qry = $dbcon->query($q);
    $qry->setFetchMode(PDO:: FETCH_OBJ);

    return $qry;

}


echo "<table>";

/*Get Colums Names in table row */
$columns = array();

$qry1= qry("SHOW COLUMNS FROM Your_table_name");

while (@$column = $qry1->fetch()->Field) {
    echo "<td>".$column."</td>";
    $columns[] = $column;

}

echo "<tr>";

/* Fetch all data into a html table *

$qry2 = qry("SELECT * FROM Your_table_name");

while ( $details = $qry2->fetch()) {

    echo "<tr>";
    foreach ($columns as $c_name) {
    echo "<td>".$details->$c_name."</td>";

}

}

echo "</table>";

?>
于 2017-11-06T11:51:32.977 回答