0
votes

I have written a code to fetch the data from database, but its ended up with an error

A PHP Error was encountered Severity: Notice Message: Undefined index: username Filename: views/userinfo.php Line Number: 20 Backtrace:

File: D:\wamp\www\anand\codeigniter\application\views\userinfo.php Line: 20 Function: _error_handler

File: D:\wamp\www\anand\codeigniter\application\controllers\Main.php Line: 35 Function: view

File: D:\wamp\www\anand\codeigniter\index.php Line: 315 Function: require_once

My code is

?php
   $name=$this->session->username;
   $pass=$this->session->password;
   $q=$this->db->query("select * from signup where username='$name' and password='$pass'");
   $data=$q->result();
   echo $data['username'];
   echo $data['password'];
?>

kindly give a suggestion to fetch the data in a correct format..

5
use $data->username; and $data->password; - Rahul
yes, i tried that too. yet error exist.. - Samuel Anand
why are you use in session ? and can your more explain how you are handing this request - Aman Maurya
you should read this. codeigniter.com/userguide3/database/results.html understand result(), row(), result_array(). - Rahul
if you are submitting the form using POST then you can get like this $_POST['username'] ,but this not the best way to do in CI - Aman Maurya

5 Answers

0
votes

Error is rectified by using

`<?php
        foreach ($q->result() as $data)
        {
        echo $data->username; 
        echo $data->password;
        }
  ?>` 

instead of

`<?php
      $data=$q->result();
      echo $data['username'];
      echo $data['password'];
 ?>`
0
votes

Use

 print_r($data);

to know the result. It will show you the correctly result.

0
votes

Change $q->result() to $q->row_array(). It will only get an array result and you can directly access the key like $data['username']

<?php
   $name=$this->session->username;
   $pass=$this->session->password;
   $q=$this->db->query("select * from signup where username='$name' and password='$pass'");
   $data=$q->row_array();
   echo $data['username'];
   echo $data['password'];
?>
0
votes

if there is only one row of result use result_array();

  $data=$q->result_array();
  echo $data[0]['username'];
  echo $data[0]['password'];
0
votes

You should use this

$q->result_array();
foreach($q as $data):

echo $data['username'];
echo $data['password'];

endforeach;

If you use $q->result() then in the foreach do like this

echo $data->username;