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 utf8mb4_unicode_ci in MySQL with PHP?
- How to use a variable in a MySQL query using PHP?
- How to export data from MySQL to Excel using PHP?
- How to change database in MySQL with PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the first row of a result in MySQL using PHP?
- How to check the result of an insert in PHP and MySQL?
- How to list databases in PHP and MySQL?
- How to generate a UUID in MySQL using PHP?
- How to get the version of MySQL using PHP?
See more codes...