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 call a stored procedure in MySQL using PHP?
- How to get a key-value array from a MySQL database using PHP?
- How to join tables with PHP and MySQL?
- How to use a MySQL union in PHP?
- How to generate a UUID in MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to create pagination in MySQL using PHP?
- How to fetch data from MySQL in PHP?
- How to escape a string for MySQL in PHP?
See more codes...