如何在codeigniter中获取mysql表的字段名?

时间:2012-04-21 10:30:37

标签: php mysql sql codeigniter

我是codeigniter的新手。我正在尝试获取带有查询的表的字段名称。

我写了一个查询

  

“select * from user”

并将其传递给$this->db->query()函数。我正在获得记录。但我想得到表的字段名称。那我该怎么办呢?

是的,请有人帮助我。提前谢谢。

6 个答案:

答案 0 :(得分:34)

使用数据库库编写此代码以列出所有字段:

$this->db->list_fields('table')

看看这里:http://www.codeigniter.com/user_guide/database/results.html#CI_DB_result::list_fields

答案 1 :(得分:9)

有些时候这可能会有所帮助

$fields = $this->db->field_data('table_name');

foreach ($fields as $field)
{
   echo $field->name;
   echo $field->type;
   echo $field->max_length;
   echo $field->primary_key;
}

答案 2 :(得分:3)

你所做的是从表格中获取数据.... 这里你的表是用户

模型函数中的

执行此操作...

function get_field()
{
$result = $this->db->list_fields('user');
foreach($result as $field)
{
$data[] = $field;
return $data;
}
}
控制器中的

执行此操作

function get_field()
{
$data['field'] = $this->model_name->get_field();
$this->load->view('view_name',$data);
}
在您的视图中

执行此操作

foreach($field as $f)
{
echo $f."<br>"; //this will echo all your fields
}

希望这会对你有所帮助

答案 3 :(得分:0)

您可以使用以下代码从db

中获取字段
$fields = $this->db->list_fields('table_name');

foreach ($fields as $field)
{
   echo $field;
}

答案 4 :(得分:0)

在此代码的帮助下,我们可以从db

中获取字段名称
include('db.php');

    $col="SHOW COLUMNS FROM `camera details`";
    $output=mysqli_query($db,$col);

    $kal=array();
    while($row=mysqli_fetch_array($output))
    {
        if($row['Field']!='id')
        {
            ?><div class="values"><?php echo $row['Field'];
            echo "<br>";?></div><br><br><?php
            array_push($kal, $row['Field']);
        }
    }
    ?>
    <?php** 

答案 5 :(得分:0)

The answer given above by Anwar needs modification, there is no need for foreach loop in model function as it will only give the first element despite using foreach, which means the foreach loop is not bringing the fields using $data[], below code should give you 100% result

in your model function do this...

function get_field()
{
$result = $this->db->list_fields('user');
return $result();
}
in your controller do this

function get_field()
{
$data['field'] = $this->model_name->get_field();
$this->load->view('view_name',$data);
}
in your view do this

foreach($field as $f)
{
echo $f."<br>"; //this will echo all your fields
}