select-from-where query not working in codeigniter model - php

I am trying to select the details of the users from a table in mysql database but it is not working. This is the code in my model :-
public function getuserdetails()
{
$user_email = $this->input->post('email');
$query_userdetails = $this->db->query("SELECT *
FROM users WHERE email = '$user_email' ");
return $query_userdetails->result_array();
}
This is not working. But if I put the actual email id in the query instead of $user_email it works but not properly i.e if I use :-
$query_userdetails = $this->db->query("SELECT * FROM users WHERE
email = 'myemail#gmail.com' ");
In this case it returns a result. My controller code to accept the result is :-
$data['details'] = $this->model_userdetails->getuserdetails();
But the problem is that when I access $details in view :-
echo $details['name']."<br />";
it does not recognize 'name'. name is the field in the database where the name of the users are stored. But if I try to retrieve it in a foreach loop it is working :-
foreach($details as $udetails)
{
echo $udetails['name']."<br />";
}

Run queries as per codeigniter suggestion
$query_userdetails = $this->db->query("SELECT * FROM users WHERE email = ?", array($user_email));
http://ellislab.com/codeigniter/user-guide/database/queries.html search for Query Bindings

I would try:
$query_userdetails = $this->db->query("SELECT * FROM users WHERE email = '". $user_email ."'");

I have solved the part where only foreach loop would work.
If we use row_array instead of returning result_array() the foreach constraint to diplay goes away.
Now I want to select the name from the database where email is $user_email

You have to write like this
public function getuserdetails()
{
$user_email = $this->input->post('email');
$this->db->where('email', $user_email)
->get('users')
->result_array();
}
After this, in view, you must to write like this
foreach($details as $udetails)
{
echo $udetails['name']."<br />";
}

You can try like This:
[CONTROLLER]
$data = array();
$data['udetails'] = $this->UserModel->getuserdetails();
$this->load->view('welcome_message',$data);
[MODEL]
public function getuserdetails() {
$user_email = 'webmaster';
$userdetails = $this->db->query("SELECT * FROM users WHERE umail = '$user_email' ");
return $userdetails->result();
}
[VIEW]
<?php
foreach($udetails as $row)
{
echo($row->uname.'<br/>');
echo($row->uname);
}
?>

Try this please it will help you.
Model
public function getuserdetails()
{
$user_email = $this->input->post('email');
$this->db->select("*");
$this->db->from('users');
$this->db->where('email',$user_email);
$query = $this->db->get();
$result= $query->result();
}
Controller
$data['details'] = $this->model_userdetails->getuserdetails();
view
foreach($details as $detail)
{
echo $detail->name;
echo $detail->email;
}

Related

Use Equation Variable in Codeiginiter

Hi guys I tried to use the variable equation on Codeigniter as in the code I wrote below, Is my code writing correct? and here's my code so far I wanna using variable $amount in my controller
In Controller
$amount = $this->m_data->getTotalSales->$data['TOTAL_SALES'];
and this in Model
//GET TOTAL REVENUE
function getTotalSales(){
$this->db->select("(SELECT SUM(grand_total) FROM sales_order WHERE member = ".$this->session->userdata('ID').") - (SELECT SUM(amount) FROM payment WHERE member_id = ".$this->session->userdata('ID').") AS total_sales");
$query = $this->db->get();
if ($query->num_rows() >0){
foreach ($query->result() as $data) {
$hasilSemua[] = $data;
}
return $hasilSemua;
}
}
$amount = $this->m_data->getTotalSales();
function getTotalSales(){
$result1 = $this->db->select_sum("grand_total")
->from('sales_order')
->where("member = $this->session->userdata('ID')");
->get();
$result2 = $this->db->select_sum("amount")
->from('payment')
->where("member_id = $this->session->userdata('ID')")
->get();
return $result1->row()-$result2->row();
}
}
I believe this is what you are after. Note that I pass the UserID in as the second parameter to the WHERE function. This is in case there is any chance of the user having inputted it (always safter to do this anyway).
//GET TOTAL REVENUE
function getTotalSales(){
$db = $this->db;
$db->select('SUM(grand_total)');
$db->where('member',$this->session->userdata('ID'));
$q1 = $db->get_compiled_select('sales_order');
$db->select('SUM(amount)');
$db->where('member_id',$this->session->userdata('ID'));
$q2 = $db->get_compiled_select('payment');
$query = $db->query("SELECT ($q1) - ($q2) as total_sales");
$data = $query->row_array();
return $data['total_sales'];
}
You can then call $amount = $this->m_data->getTotalSales; to get your result.

Cannot use $this->uri->segment(); in WHERE clause

I have a simple query but I am trying to use $this->uri->segment(); in WHERE clause
I could not get it working.
Any suggestions would be greatly appreciated.
In my controller I have:
public function profile()
{
$var = (int) $this->uri->segment(3);
$query = $this->db->query('SELECT * FROM faculty WHERE id = $var;');
$data['name'] = '';
$data['section'] = "Profile";
$data['query'] = $query;
$this->load->view('view1', $data);
}
PHP won't evaluate variables inside string literals (' ').
Change
'SELECT * FROM faculty WHERE id = $var;'
to
"SELECT * FROM faculty WHERE id = $var;"

select all and some attribute from a table get different result in codeigniter

I've try to get result from sql query in codeigniter with mode select all attribute but it returns a PHP error but when I specify some attribute in give the right answer but the query is too long to be written.
This 2 mode select that I've try and give different result.
First
class model_kemiskinan extends CI_Model {
..... //constructor here
function get_kemiskinan_provinsi(){
$this->tahun = "2011";
$this->kodeProv = "31";
$this->query = "select * from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;
$this->result = $this->db->query($this->query);
return $this->result->result();
}
Then the controlller pass it
public function testquery(){
$this->load->model('model_kemiskinan');
$data['hasil'] = $this->model_kemiskinan->get_kemiskinan_provinsi();
$data['main_content'] = 'test';
$this->load->view('template', $data);
}
and the view 'test' respond it with these code:
if(is_array($hasil)){
foreach ($hasil as $baris ) {
echo $baris->tahun;
echo $baris->id_provinsi;
echo "<br/>";
}
And the result is this
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$tahun
Second
But if I change the select mode that look like this :
$this->query = "select tahun, id_provinsi from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;
It will work properly
Is there any solution about select all mode?
-Thanks before-
like the documentation (http://ellislab.com/codeigniter/user-guide/database/examples.html) says:
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->email;
}
echo 'Total Results: ' . $query->num_rows();
you get only one row by calling result() so you need to call it by foreach:
function get_kemiskinan_provinsi(){
$this->tahun = "2011";
$this->kodeProv = "31";
$this->query = "select * from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;
$this->result = $this->db->query($this->query);
$res = array();
foreach ($this->result->result() as $row)
{
$res[] = $row;
}
return $res;
}
Please recognize that the fields in the result object are case sensitive! If you have a field named "Tahun" in your db then "select tahun ..." will work in mysql and will give you an object where you can access $res->tahun.
If you do "select * ...." then you can only access it like this: $res->Tahun (with capial T)

Get all favorites for current user

I've got a table in the database called "favorites" with 3 columns (user_id, bookmarked_song_id, bookmark_tag) and I want to get all the Bookmarked_song_id for the current user.
$username = $this->session->userdata('username');
$uidq = mysql_query('SELECT user_id FROM users WHERE username="' . $username . '"');
$rq = mysql_fetch_assoc($uidq);
$user_id = $rq['user_id'];
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
$favsr = mysql_fetch_array($getfavq); //contains all the information from the favorites database where user_id is the user_of the currently logged-in user
And I don't know what to use next... I want to have something like:
foreach($favsr['bookmarked_song_id'] as $song_id) {
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_assoc($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
Obviously the method is wrong because I get: "Invalid argument supplied for foreach()". Can anyone help me with getting the songs? Thanks in advance.
It should be this:
$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC);
foreach($favsr as $row) {
$songid = $row['bookmarked_song_id'];
...
}
mysql_fetch_array only loads one row,
it should be like that
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
while $favsr = mysql_fetch_array($getfavq);
{$songid=$favsr['bookmarked_song_id'];
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_array($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
You have this tagged with codeigniter. If you've building a CodeIgniter application, you should probably use CI's database library:
$username = $this->session->userdata('username');
//Select your user
$this->db->select('user_id');
$this->db->where('username', $username);
$this->db->limit(1);
$user_query = $this->db->get('users');
if($user_query->num_rows() > 0)
{
// We found a user
$user = $user_query->row(); // select a single row
// Grab this user's favorites
$this->db->where('user_id', $user->id);
$favorites_query = $this->db->get('favorites');
$songs = $favorites_query->result();
if($songs)
{
foreach($songs as $song)
{
$song_id = $song->bookmarked_song_id;
$tag = $song->bookmark_tag;
// Do stuff with data.
}
}
else
{
// No songs/favorites found, catch error
}
}
else
{
// No such user found, catch error
}
Of course, the best practice is to have your user data and your favorites data in separate models, but this should work for now.

CodeIgniter passing array with queries into view

Hi I am having an issue getting the view to show any results for the following code.
Controller:
$datedue = 2011-01-27;
$username = $this->tank_auth->get_username();
$sql = "SELECT taskid FROM relationships WHERE username = ? AND datedue = ?";
$tasks = $this->db->query($sql, array($username, $datedue));
$count = 0;
$taskdetails = array();
foreach($tasks->result() as $row)
{
$taskid = $row->taskid;
$subsql = "SELECT * FROM tasks WHERE id = ?";
$taskdetails[$count] = $this->db->query($subsql, array($taskid));
$count++;
}
$data['taskdetails'] = $taskdetails;
$data['total'] = $count;
$this->header();
$this->load->view('dashboard', $data);
View:
<?php
foreach($taskdetails as $entry)
{
foreach($entry->result() as $row)
{
echo $row->name;
}
}
?>
Any help would be nice thanks.
The reason why your view is not displaying something is because you're query is not completely correct.
$datedue = 2011-01-27;
should be enclosed in quotes, since the date is a string.
$datedue = "2011-01-27";
Also, you're not correctly following the concept of MVC. All the database querying and results should occur inside of the Model. And all of the data handling inside the Controller.
The Controller nor the View should handle any of the database connections, that is the duty of the Model. Therefore I would advise to create a Model and put all of the Database querying in one or two functions. The Controller would then call these functions and receive the data back. Then it should manipulate it and pass it to the View in a clean matter (by this I mean, that the View should NEVER call result()
Here is how you're code should be structured:
CONTROLLER
class Tasks extends Controller {
function Tasks ()
{
parent::Controller();
$this->load->model('tasks_model');
$this->load->database();
}
function index()
{
$datedue = "2011-01-27";
$username = $this->tank_auth->get_username();
$tasks = $this->tasks_model->getTasks($username, $datedue);
$count = count($tasks);
$data['taskdetails'] = $tasks;
$data['total'] = $count;
$this->header();
$this->load->view('dashboard', $data);
}
}
MODEL
class Tasks_model extends Model {
function Tasks_model()
{
// Call the Model constructor
parent::Model();
}
function getTasks($username, $datedue) {
$sql = "SELECT taskid FROM relationships WHERE username = ? AND datedue = ?";
$tasks = $this->db->query($sql, array($username, $datedue));
$taskdetails = array();
foreach($tasks->result() as $row){
$taskid = $row->taskid;
array_push( $taskdetails, $this->getTasksDetails( $taskid ) );
}
return $taskdetails;
}
function getTasksDetails($taskid) {
$subsql = "SELECT * FROM tasks WHERE id = ?";
$taskdetails = $this->db->query($subsql, array($taskid));
return $taskdetails->row();
}
}
VIEW:
foreach($taskdetails as $task)
{
echo $task->name;
}
verify your task table contain the name field
view
foreach($taskdetails as $entry)
{
foreach($entry->result() as $row)
{
echo $row[0];
}
}
why you are passing array in this line
$taskdetails[$count] = $this->db->query($subsql, array($taskid));
instead write
$taskdetails[$count] = $this->db->query($subsql, $taskid);

Categories