Write a function in PHP that can receive a table name, then print the header of the table and record it on the web page

<?php

    function show_table_info($table_name){

        $conn = mysql_connect("localhost" , "root" , "root");
        if(!$conn){
            die('连接失败'.mysql_error());
        }

        mysql_select_db("test1",$conn);
        mysql_query("set names gbk");
//      $sql = "select * from user1";
        $sql = "desc user1";
        $res = mysql_query($sql , $conn);

        //获取结果集的行数、列数
        $rows = mysql_affected_rows($conn);  //参数是连接
        $cols = mysql_num_fields($res);      //参数是返回的资源
        echo "行:".$rows."<br>列:".$cols;

        //打印表头
        echo "<table border=1 cellspacing=0><tr>";
        for($i=0; $i<$cols; $i++){

            //取字段
            $mysql_name = mysql_field_name($res,$i);
            echo "<th>".$mysql_name."</th>";
        }
        echo "</tr>";

        while ($row = mysql_fetch_row($res)){
            echo "<tr>";
            for($i=0; $i<$cols; $i++){
                echo "<td>$row[$i]</td>";
            }
            echo "</tr>";
        }
        echo "</table>";

//         while($field_info = mysql_fetch_field($res)){
//             echo "<br>".$field_info->name;
//             /*打印结果:
//              * 
//                 id
//                 name
//                 password
//                 email
//                 age*/
//         }
        //var_dump($field_info);

    }

    show_table_info("user1");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688283&siteId=291194637