I am trying to join two tables and return an array in my Model method in CodeIgniter with php. I've gone through a few previously posted similar questions on stackoverflow and modified my code accordingly. But they don't seem to work. Hence would love to know what's wrong with the following.
I'm using the following method but am currently getting exceptions. Would appreciate suggestions in this regard.
Model Method
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
$this->db->select('s.uid, s.name,s.phone, s.studentId, s.type, sp.profiledesc, sp.age');
$this->db->from('sysuser as s');
$this->db->join('studentprofile as sp', 's.uid = sp.uid', 'left');
$this->db->where(array('s.uid' => $uid));
$query = $this->db->get();
return $query->result();
}
Controller
$data1['details'] = $this->userModel->getUserDetails($username);
$this->load->view('studentDashboard/viewProfile',$data1);
View
...
<h2>
<?php foreach($details as $detail){?>
<?php echo $detail->s.name;?>
<?php }?>
</h2>
...
In the view, I've also tried just echoing $detail->name but this doesn't work either.
At first, use print_r($details) for checking your data. If it's returning anything or not.
Then echo your value like this $detail['name']
Fixed Code:
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
$this->db->select("*");
$this->db->from('sysuser');
$this->db->join('studentprofile', 'studentprofile.uid = sysuser.uid');
$this->db->where('sysuser.uid',$uid);
$query = $this->db->get();
return $query->result();
}
Look, i´m not sure that i understood your code, what means this line
$uid = $this->getUserUid($username);
You´re calling a method and sending the name to retrieve the userid, right?
I´ll write that method like you should have it:
public function getUserid($user){
$this->where->id($user);
return $this->get('whatever table')->row();
//i think you forgot this ->row()
}
then
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
//here already you should bring with ->row() already
//you can use this var_dump here to confirm too
//var_dump($uid);
//exit;
$this->db->select('s.uid, s.name,s.phone, s.studentId, s.type, sp.profiledesc, sp.age');
//line´s right
//the from method is disposable, so i put it into the get but here it´s right too
$this->db->join('studentprofile as sp', 's.uid = sp.uid', 'left'); //ok
$this->db->where($uid); //this line is the wronger, i´ve made the fix
//as this is an where, you´d bring only one value with ->row() from that other method
$query = $this->db->get('sysuser as s');
//the 'from' i putted here, just to write a line less
return $query->result();
when you need to test what you´re returng do a var_dump here
//commenting the return above
//$test = $query->result();
//var_dump($test);
}
Related
I'm a rookie on codeigniter and I'm trying to solve a problem where I try to get some images from the database using a foreach cicle
I have this on my controller to get the images
$data['products'] = '.base_url('$this->Cart_model->get_img()').';
and this on my model
public function get_img()
{
$sql = "SELECT image FROM products";
$query = $this->db->query($sql);
return $query->result_array();
}
In my view it get me a syntax error beacause something is wrong in the controller
Already checked the View.tpl and everything is fine, must be something in the controller
You forgot the concatenation operator to concatenate the strings.
$data['products'] = '.base_url(' . $this->Cart_model->get_img() . ').';
I use this code to display data according to the user who is logged in, and display their data.
but with this syntax the data that appears does not match the defined data, and also other user data sometimes appears too.
$id=$this->session->userdata('ses_id');
$this->db->SELECT('*');
$this->db->from('doc_priv_std');
$this->db->join('acc',' doc_priv_std.id_acc=acc.id_acc');
$this->db->where('doc_priv_std.id_acc ',$id,('and
type_doc LIKE "%.doc%"
or "%.docx%"
or "%.pdf"
or "%.xls%"
or "%.xlsx%"
or "%.ppt%"
or "%.pptx%"
or "%.zip%"
or "%.rar%"'));
$query = $this->db->get();
return $query->result_array();
please help so that the data that appears as defined.
Your syntax is wrong - you can't do this with your way - you have to organise your Query properly - try the following
$id=$this->session->userdata('ses_id');
$arrExtension = ['.docx', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx', '.zip', '.rar'];
$this->db
->select('*')
->from('doc_priv_std')
->join('acc',' doc_priv_std.id_acc=acc.id_acc')
->where('acc.id_acc', $id)
->group_start();
foreach($arrExtension AS $strExtension)
{
$this->db->or_like('type_doc', $strExtension);
}
$query = $this->db->group_end()->get();
return $query->result_array();
Use var_dump($this->db->last_query()); before your return to see the db query you are actually running to help with debugging, but it could be that you where statement is wrong? Try this instead:
$where = 'WHERE type_doc LIKE "%.doc%"
or "%.docx%"
or "%.pdf"
or "%.xls%"
or "%.xlsx%"
or "%.ppt%"
or "%.pptx%"
or "%.zip%"
or "%.rar%"';
$this->db->select('*')
->join('acc',' doc_priv_std.id_acc=acc.id_acc')
->where('doc_priv_std.id_acc', $id)
->where($where);
$query = $this->db->get();
return $query->num_rows() > 0 ? $query->result_array() : FALSE;
I'm trying to create a function that runs a query that returns all of the data located in my MySQL database.
My current code only returns the one row of data (there are 7)
function staff_get() {
$this->load->database();
$sql = 'SELECT * from Staff';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
}
I'd imagine it has something to do with the line "$data = $query->row();" however I've tried switching "row" with "array" but this doesn't work. The text is designed to come out as plaintext so that I can manipulate it using a jQuery template.
Thank you for your help in advance.
You need to encase the results in a while loop. Something along the lines of this.
function staff_get() {
$this->load->database();
$sql = 'SELECT * from Staff';
$query = $this->db->query($sql);
while($data = $query->row()) {
$this->response($data, 200);
}
}
I have the following function that does not work and I'm having the hardest time trying to figure it out. I'm 12 and just learning, so forgive me:
function get_answer() {
$answer = $this->db->query("SELECT COUNT(questions) FROM possible_quest WHERE questions='something'");
return $answer;
}
When I run the following SQL query in phpmyadmin, it returns the expected result
SELECT COUNT(questions) FROM possible_quest WHERE questions='something'
How do I get this working in CodeIgniter using my function above?
The PHP error I get is
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Could be:
function get_answer()
{
$query = $this->db->query("SELECT COUNT(questions) AS count FROM possible_quest WHERE questions='something'");
$count = $query->row(); // returns an object of the first row
return $count->count;
// OR
$count = $query->row_array(); // returns an asociative array of the result
return $count['count'];
}
Another thing: if you want to pass 'something' as a variable, you can use parametrized query, like
$sql = "SELECT COUNT(questions) AS count FROM possible_quest WHERE questions = ?";
$query = $this->db->query($sql, array($something));
which has the benefit of escaping automatically your variable, so you don't worry about sql injections.
You need to setup to the count.
Heres what you need to do is
$answer = $this->db->query("SELECT COUNT(questions) as count FROM possible_quest WHERE questions='something'")->first_row()->count;
//$answer is now setup to be count
One line. Thats the beauty of CI
You're getting that error because
return $answer;
should be
return $answer->result();
The error you are getting is related to the fact that $this->db->query returns a result object, so you cannot use $answer directly as a string.
I suggest that you use print_r($answer) to see what could be going wrong with your conversion of objects to strings, if you have such a function in your model.
CodeIgniter has functions for building queries and returning the count:
function get_answer() {
$this->db->from("possible_quest");
$this->db->where("questions", "something");
return $this->db->count_all_results();
}
NOTE: The name of the function 'get_answer' doesn't match what you're actually doing. It looks like you're getting a count of questions, not an answer, so you should name it to something that makes more sense, like 'get_question_count'.
I recommend you to use an Active Record with method chaining when possible:
public function getAnswer() {
return
$this->db->
select('id')->
where('questions', 'something')->
get('possible_quest')->row()->count
;
}
or
public function getAnswer() {
return
$this->db->
select('id')->
from('possible_quest')->
where('questions', 'something')->
get()->row()->count
;
}
It's secure, easy to use, easy to understand and read. Don't listen to people saying that a single-line code is something good because a good code should be readable.
I'm trying to submit an update function, but for some reason it's not working and I can't figure out why... Someone who does?
UPDATE SQL-SYNTAX:
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
INSERT FUNCTION:
public function insert($sql) {
mysql_query($sql, $this->_connection);
return mysql_affected_rows($this->_connection);
}
PHP:
$project = new Project();
$project->name = $_POST['newproject_name'];
$project->photo1 = $_FILES['images']['name'][0];
if($project->updateProject($_DB, $projectname)) {
$feedback = "OK!";
} else {
$feedback = "NOT OK!!";
}
And in case you were wondering, $project->name and $project->photo1 are filled in correctly.
Any ideas? I hope I gave you everything you need, if not, let me know!
EDIT 1: I used the 2 first answers, but no results. Yet...
EDIT 2: I also don't get anything from $feedback
It looks like you have a stray opening parenthesis after the SET keyword. Remove it.
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
public function updateProject($db, $id)
requires 2 parameters being passed but when you do
if($project->updateProject($_DB))
you're only passing 1??
Your updateProject needs two variables and the second one is missing in your call, resulting in an invalid query.
Edit: Based on your edit; I'm guessing $id needs to be an integer or a string, you are passing an object.
Exactly what row do you want to update? I don't see anything in your php code that defines the ID of the row you want to modify, you are just generating a new object, not getting one from a database for example.