Is it possible to list the columns used in a SELECT in PHP mysqli?

Asked

Viewed 344 times

2

I have the query

SELECT coluna1, coluna2... FROM tabela 

I wonder if there’s any method in the class mysqli to return these columns that were used in the query, even if the query does not return records. In a query returning records I can simply use array_keys() in the method fetch_assoc(). But I can’t if the query do not return records, since there will be no indexes.

I need to do this because it’s a query great, and would like such a process to be done dynamically.

1 answer

2


To retrieve the columns used in select use the function/method fetch_fields() which returns information like column name, type, size etc.

$db = new mysqli('localhost', 'usuario', 'senha', 'base');

$result = $db->query('SELECT col1, col2, col3 FROM tabela');

$fields  = $result->fetch_fields();

foreach($fields as $item){
    echo $item->name .'<br>';
}

The return is an object with the following properties:

stdClass Object
(
    [name] => col1
    [orgname] => col1
    [table] => tabela
    [orgtable] => tabela
    [def] => 
    [db] => base
    [catalog] => def
    [max_length] => 0
    [length] => 1
    [charsetnr] => 8
    [flags] => 0
    [type] => 254
    [decimals] => 0
)       

Browser other questions tagged

You are not signed in. Login or sign up in order to post.