I am new in both php and mysql. I want to create a dynamic table that will have all fields from table in mysql database. I am trying to get all column names in an array but fail to do. I am trying following code:
<?php
$fields = mysql_query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'mytablename' ");
$res = mysql_fetch_array($fields);
foreach ($res as $field)
{
echo '<tr>';
echo '<td>';
echo $field;
echo '</td>';
echo '<td>';
echo "<input type='text' class='' name='tags' id='tags' value=''>";
echo '</td>';
echo '</tr>';
}
?>
Any assistance would be appreciated.
You dont need an additional SQL query just to get your field names. You can use your normale SELECT query and just get your field names (and definition) from that query. Better performance this way!
Deprecated MySQL Solution:
The MySQL Library is deprecated. It can be used as in this link, btu you should switch to the mysqli Library which is nearly identical when used proceduraly (second sample).
htttp://www.php.net/manual/en/function.mysql-field-name.php
The OOP MySQLi Solution:
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
The Procedural MySQLi Solution:
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
http://www.php.net/manual/en/mysqli-result.fetch-field.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With