php-mysqlHow to get table column names in PHP MySQL?
To get the column names of a table in PHP MySQL, you can use the mysqli_fetch_fields() function. This function returns an array of objects containing the column names.
Example code
$conn = mysqli_connect("localhost", "username", "password", "database");
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$columns = mysqli_fetch_fields($result);
foreach ($columns as $column) {
echo $column->name . "\n";
}
Output example
column1
column2
column3
Code explanation
mysqli_fetch_fields($result): This function takes the result of a query as an argument and returns an array of objects containing the column names.$column->name: This is used to access the name of each column in the array of objects returned bymysqli_fetch_fields().
Helpful links
More of Php Mysql
- How to use a MySQL union in PHP?
- How to get the last insert ID in PHP MySQL?
- How to output XML from MySQL using PHP?
- How to change database in MySQL with PHP?
- How to export data from MySQL to Excel using PHP?
- How to list tables in PHP MySQL?
- How to list databases in PHP and MySQL?
- Inserting data to MySQL using PHP
- How to escape a string for MySQL in PHP?
See more codes...