Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php、mysql,如何在动态sql html表循环中获取字段名?_Php_Mysql - Fatal编程技术网

php、mysql,如何在动态sql html表循环中获取字段名?

php、mysql,如何在动态sql html表循环中获取字段名?,php,mysql,Php,Mysql,我想根据循环中的字段名做一些不同的事情。我的代码根据sql查询中使用的字段动态生成html表。如果循环中的字段是主键,我想生成指向某个页面的链接。。。有什么想法吗 我已经在这里标记了需要获取字段名的位置 if (mysql_num_rows($result)>0) { //loop thru the field names to print the correct headers $i = 0; while ($i < mys

我想根据循环中的字段名做一些不同的事情。我的代码根据sql查询中使用的字段动态生成html表。如果循环中的字段是主键,我想生成指向某个页面的链接。。。有什么想法吗

我已经在这里标记了需要获取字段名的位置

    if (mysql_num_rows($result)>0) {
        //loop thru the field names to print the correct headers
        $i = 0;

        while ($i < mysql_num_fields($result)) {
            $out .= "<th bgcolor='#CFCFCF'><font size=2>". mysql_field_name($result, $i) . "</font></th>";
            $i++;
        }
        echo "</tr>";

        //display the data
        while ($rows = mysql_fetch_array($result,MYSQL_ASSOC)) {
            $out .= "<tr>";
            foreach ($rows as $data) {
                //HERE
                $out .= "<td bgcolor='#DCDCDC'><font size=2>". $data . "</font></td>";
            }
        }
    }
if(mysql\u num\u行($result)>0){
//循环遍历字段名称以打印正确的标题
$i=0;
而($i
我认为唯一的方法是事先进行查询

结果中的“键”列将为您提供每列的键状态。您可以从中找到并保存主键的位置,并相应地输出该列的HTML。

尝试以下操作:

if (mysql_num_rows($result)>0) {
    //loop thru the field names to print the correct headers
    $i = 0;

    while ($i < mysql_num_fields($result)) {
        $out .= "<th bgcolor='#CFCFCF'><font size=2>". mysql_field_name($result, $i) . "</font></th>";
        $i++;
    }
    echo "</tr>";

    //display the data
    while ($rows = mysql_fetch_array($result,MYSQL_ASSOC)) {
        $out .= "<tr>";
        foreach ($rows as $colName=>$data) {
            if($colName == 'keyname'){
                doStuff();
            }else{
                $out .= "<td bgcolor='#DCDCDC'><font size=2>". $data . "</font></td>";
            }
        }
    }
}
然后生成的数组将如下所示

array( "othername" => 1, "PhoneNumber" => '0035 2500 65887')
编辑: 如果您需要知道某个ColName是否是主键,请使用

if( mysql_num_rows(mysql_query("'SHOW INDEXES FROM day WHERE Column_name = '$colname' AND Key_name = 'PRIMARY'")) > 0){
    //is a primary key
}else{
    //is not a primary key
}

我知道这是可能的,但我不知道如何在这种情况下做到这一点loop@Jules你不能单独在循环中完成。您必须事先在单独的查询中找到主键字段的名称;然后可以将其与循环中当前字段的名称进行比较
if( mysql_num_rows(mysql_query("'SHOW INDEXES FROM day WHERE Column_name = '$colname' AND Key_name = 'PRIMARY'")) > 0){
    //is a primary key
}else{
    //is not a primary key
}