简体   繁体   中英

Fetching a value from database in codeigniter

I am trying to fetch some values from the database and I'm getting this error

A PHP Error was encountered
Severity: Notice
Message: Undefined index: name
Filename: views/pro_view.php
Line Number: 12

My controller:

$this->load->model('profile_model');

$data['profile_data'] = $this->profile_model->get_records();

$this->load->view('pro_view', $data);

Model:

function get_records()
{
    $r = $this->uri->segment(3);
    $query = $this->db->get_where('profile', array('id' => $r));
    return $query->result();
}

View:

<input type="text" name="name" value="<?php echo $profile_data["name"]  ?>" />

if I var_dump(($profile_data); I'm getting everything in an array.

I read other similar questions and their answers, no luck.

If you need to fetch single row then use

$query = $this->db->get_where('profile', array('id' => $r));
$ret = $query->row();
return $ret->name;

Controller

$data['name'] = $this->profile_model->get_records();

$this->load->view('pro_view', $data);

View

<input type="text" name="name" value="<?php echo $name;?>" />

And for your present code you need to use foreach loop

 foreach (profile_data as $row)
   { ?>
<input type="text" name="name" value="<?php echo $row->name;?>" />

  <?php }?>

result()

This method returns the query result as an array of objects, or an empty array on failure. Typically you'll use this in a foreach loop

Controller

    $this->load->model('profile_model');

    $data['profile_data'] = $this->profile_model->get_records();

    $this->load->view('pro_view', $data);

Model

$r = $this->uri->segment(3);
$this->db->select('*');
$this->db->from('profile');
$this->db->where('id',$r);
$q = $this->db->get();
if($q->num_rows() > 0){
$row = $q->row();
return $row->name;
}
return false;

view

<input type="text" name="name" value="<?php echo $name;?>" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM