如何使用PHP从MYSQL数据库获取列类型并将其存储在变量中


How to get column type from a MYSQL database using PHP and store that in a variable

我正在开发一个PHP应用程序,该应用程序有一个侧菜单栏,其中包含指向不同页面的链接列表,以显示不同的表格。此应用程序具有创建新的侧菜单项并将其添加到列表中的功能,并且应该能够在单击它时显示自己的表,为此我创建了一个所有侧菜单项通用的表生成器文件,因此它重定向到具有默认表模板的同一文件,但显示单击的菜单项的表。我添加了新数据并更新了要应用于应用程序本身中创建的那些新表的数据功能。所以现在它根据单击的链接显示不同的数据库表,每次为不同的页面显示一个新表时,我想写一个通用的更新语句,该语句将根据加载的表而变化。问题是我想要正在加载的列的类型,以便我可以使用 switch 语句根据存储的列类型将值添加到更新语句中,例如文本等的引号('')。

我尝试使用mysqli_fetch_field_direct函数并尝试将字段类型存储在变量中,但该变量存储数字而不是字段类型。

提前感谢您的帮助。这是我的第一个问题,请不要介意这个问题的结构不好。

$columns= mysqli_query($conn,"SHOW COLUMNS FROM test_table"); // Selecting column titles of the table
$array = array(); // Creating the array that will contain column names
$i = 1; // Columns number
$j = 0; 
$fType = array();
while ($row = mysqli_fetch_assoc($columns)) {
     if($row['Field'] != 'id'){
         while ($i <= sizeof($array)) {
             $name = "text";
             $var = $name . $i; // This variable is the name of the input field in the front end
             $fType[] = $columns->fetch_field_direct($i)->type; //fetch field type and store in the array
             $i++;
         }
     }
     $array[] = $row['Field']; // Saving the name of each column in an array
}

我认为这就是您要做的。

$q = mysql_query('DESCRIBE tablename');
while($row = mysql_fetch_array($q)) {
    echo "{$row['Field']} - {$row['Type']}'n";
}