Welcome Guest, Not a member yet? Register   Sign In
Reading database data in a view
#1

[eluser]Tanag[/eluser]
Really simple question here. I'm making a call to my database that grabs a single record based on a user ID. I can't seem to read that record on my view without using a loop though. Im sure I just don't have the really simple syntax right, but I can't get it.

Here is my controller code:

Code:
$this->db->where('user_id', $data['users']);
$data['query'] = $this->db->get('users');
$this->load->view('welcome_view', $data);

That works fine, and I can view the data if I do this:

Code:
<?php foreach($query->result() as $row): ?>

<p>&lt;?=$row->user_id?&gt;</p>
<p>&lt;?=$row->class?&gt;</p>

&lt;?php endforeach; ?&gt;

But using a loop seems pointless. I know there will always be one record as the user_id is my unique field.
So how can I read the data like $query->result() as $row does. Like I want something like $query->user_id.

Any help would be great, thanks. Im sure its a simple solution and I am a dummy.
#2

[eluser]mohsin917[/eluser]
use this in foreach

foreach($query as $row):
#3

[eluser]mohsin917[/eluser]
Sorry for the previous reply it will not work..

Code:
$this->db->where('user_id', $data['users']);
$query = $this->db->get('users');
$data['query'] = $query->result();
$this->load->view('welcome_view', $data);


Code:
&lt;?php foreach($query as $row): ?&gt;

<p>&lt;?=$row->user_id?&gt;</p>
<p>&lt;?=$row->class?&gt;</p>

&lt;?php endforeach; ?&gt;

This should work..
#4

[eluser]K-Fella[/eluser]
If you only expect one row from the database then use:
Code:
$data['user'] = $query->row(); // using row() instead of result()

Then in your view you can call:
Code:
$user->id // $user->name, etc

No need for loops.
#5

[eluser]Tanag[/eluser]
Hmm maybe Im doing something wrong as I still can't get it work.

Controller:

Quote:$this->db->where('user_id', $data['users']);
$data['query'] = $this->db->get('users');
$data['user'] = $query->row(); //row you had me add
$this->load->view('welcome_view', $data);

View:
Quote:&lt;?=$user->gold?&gt; gold

And I get the error:

Code:
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: query

Filename: controllers/welcome.php

Line Number: 32
#6

[eluser]K-Fella[/eluser]
The 2nd line should read:
Code:
$query = $this->db->get(‘users’);
#7

[eluser]Tanag[/eluser]
Perfect, thanks!




Theme © iAndrew 2016 - Forum software by © MyBB