MVC query join command denied - php

I should be simple enough, I have my query i return it as a variable I then set that variable as a array, the pass it into the view. how ever I get this error..
Error Number: 1142
SELECT command denied to user '******** ip.secureserver.net' for table 'Comments'
SELECT * FROM `Report_Comments`.`Comments`, `Report_Comments`.`Comment_Date`, `Login`.`Username` WHERE `ReportID` = '53'
Filename: models/report/Report_model.php
Line Number: 92
anyone see where i have gone wrong ?
Model
function get_comment()
{
$query = $this->db->get('Report_Comments.Comments, Report_Comments.Comment_Date, Login.Username')
->from('Report_Comments')
->join('Login', 'Report_Comments.UserID = Login.LoginID');
return $query->result();
}
View
<?php if (isset($reports)) :
foreach ($reports as $row) : ?>
<tr>
<td><?php echo $row->Comments; ?></td>
</tr>
<tr>
<td><?php echo $row->Comment_Date; ?></td>
</tr>
<tr>
<td><?php echo $row->Username; ?></td>
</tr>
</table>
<hr>
<?php endforeach; ?>
<?php else : ?>
<p>No Comments</p>
<?php endif; ?>
Controller
function comments()
{
$data = array();
$this->db->where('ReportID', $this->uri->segment(3));
if ($query = $this->report_model->get_comment()) {
$data['reports'] = $query;
}
$this->template['middle'] = $this->load->view($this->middle = 'comments/comment_view', $data, true);
}

New answer:
Sql is telling you the specified user does not have permission to run a select command on table Comments. You'll want to check that your user has the appropriate permissions for the db and/or table to resolve that mysql issue. Your PHP shouldn't have anything to do with that.
Original answer to original question/issue:
(The edit is throwing me off.)
In order to get a result object that includes rows you need to invoke the function that returns that object.
So in your controller
$data['reports'] = $result->result();
Variable assignment usage
Also in your model, it is useless to set $result = $this->db->get(); The return is going to just pass back $this->db->get(); - remove $result =.
And in your controller, you are testing the value of $this->report_model->get_comment() in if($result = $this->report_model->get_comment()) so, if the value is a get object then how php interprets that as true or false is somewhat loose ended - it'll return its "truthiness" which is not always straight forward. Alternatively, you could do something definite like:
$query = $this->report_model->get_comment();
if ($query->num_rows() > 0) {
$data['reports'] = $result->result();
}
You could also just pass that $query right to the view and do that test in place of your if (isset($reports)) => if ($query->num_rows() > 0): foreach ($query->result() as $row):. That would reduce one if check.
Database query builder across functions
So, you'll end up with more bugs or weird situations when you build a query through various levels of functions. Also, it's harder to maintain your codebase as it grows since you use your model function in unpredictable ways. Instead of setting the where just before calling the model function, pass the id as a parameter with a predefined value if you want it to be optional:
function get_comment($report_id = null)
{
if (isset($report_id)) {
$this->db->where('ReportID', $report_id);
}
$this->db->select('Report_Comments.Comments, Report_Comments.Comment_Date, Login.Username')
->from('Report_Comments')
->join('Login', 'Report_Comments.UserID = Login.LoginID');
return $this->db->get();
}
And your controller:
function comments()
{
$data = array();
$query = $this->report_model->get_comment($this->uri->segment(3));
if($query->num_rows() > 0)
{
$data['reports'] = $query->result();
}
$this->template['middle'] = $this->load->view ($this->middle = 'comments/comment_view',$data, true);
$this->layout();
}

Related

Message: Illegal String Offset Upgrade from Codeigniter2x Version to Codeigniter 3x version

I recently switched my project package from Codeigniter 2X version to Codeigniter 3X version.
Earlier all my code worked fine but now with new package its showing some minute errors where I am not able to run my code.
The following is the error:
Message: Illegal String Offset:
My Controller:
public function proflist(){
$data = "";
$this->load->model('feedbackmodel');
$data['teachers'] = $this->feedbackmodel->getFaculty();
$this->load->view('feedback/proflist',$data);
}
My Model:
public function getFaculty(){
$query = $this->db->query('SELECT * FROM teacher');
return $query->result_array();
}
My View:
<?php
if(!empty($teachers)) {
foreach($teachers as $y){
?>
<tr>
<td><?php echo $y->fid; ?></td>
<td><?php echo $y->fname." ". $y->lname; ?></td>
<td><?php echo $y->email; ?> </td>
<td>
...
Is there any mistake ? How shall i change it. Please let me know:) Thank You.
The reason for this is most likely the version of PHP you're using. Before PHP 7.1 it was only a Notice thrown for the use of an illegal offset. 7.1+ will now throw a Warning. You can avoid it by wrapping an 'if not, isset' in your controller around the offending array. Be sure to cast the array also.
You'll find a good explanation for it here.
public function proflist() {
$data = "";
$this->load->model('feedbackmodel');
$data['teachers'] = (array) $this->feedbackmodel->getFaculty();
if(!isset($data['teachers'])) {
$data['teachers'] = '';
}
$this->load->view('feedback/proflist',$data);
}
To be certain of the version of PHP you're running, you can use phpinfo();.
You need to be more aware of what your variable types are.
In your controller
public function proflist(){
$data = "";
$this->load->model('feedbackmodel');
$data['teachers'] = $this->feedbackmodel->getFaculty();
$this->load->view('feedback/proflist',$data);
}
You declare $data as a STRING by way of $data = "";,
Then you decide it's going to be an array by way of
$data['teachers'] = $this->feedbackmodel->getFaculty();
To be correct $data should be declared as an empty array, not an emtpy string.
public function proflist(){
$data = array(); // Using the older style of declaring an array.
$this->load->model('feedbackmodel');
$data['teachers'] = $this->feedbackmodel->getFaculty();
$this->load->view('feedback/proflist',$data);
}
Now in your Model your returned data is created via
return $query->result_array();
If you look up the codeigniter documentation on this, it will tell you that the resulting data is an Associative Array i.e $data['teachers'] will be of the form
$data['teachers']['fid'] etc.
Your View requires it to be an object.
So you can change your view which requires $teachers to be an object,from...
<?php
// $teachers should be returned from result() which is an object.
if(!empty($teachers)) {
foreach($teachers as $y){
?>
<tr>
<td><?php echo $y->fid; ?></td>
<td><?php echo $y->fname." ". $y->lname; ?></td>
<td><?php echo $y->email; ?> </td>
<td>
...
To
<?php
// $teachers is returned from result_array() which is an associative array.
if(!empty($teachers)) {
foreach($teachers as $y){
?>
<tr>
<td><?php echo $y['fid']; ?></td>
<td><?php echo $y['fname']." ". $y['name']; ?></td>
<td><?php echo $y['email']; ?> </td>
<td>
...
OR simply change the return on your model which is a one liner. So change your Model from
public function getFaculty(){
$query = $this->db->query('SELECT * FROM teacher');
return $query->result_array(); // Return an associative array
}
To
public function getFaculty(){
$query = $this->db->query('SELECT * FROM teacher');
return $query->result; // Return an object
}
So the short version is:
Check your returned array structure. You should use var_dump() for this.
Change your code to suit.
Either change the return on your model from result_array() to result() or
Change your views from addressing objects to associative arrays.
I'm pushed for time to go into any more detail at this stage, but this should help you see what is going on.

Error trying to fetch data from 2 tables codeigniter

I gotta fetch data from 2 tables.. My tables are "Study","Users" and "Subjects"
"Study" includes:(id, user_id[is the foreign key to the column "id" of the table "Users"], subject_id[is the foreign key to the column "id" of the table "Subjects"], grade, date)
"Users" includes:(id,username,name,lastname,password,type,status,date)
"Subjects" includes:(id, career_id, name, description, hours)
I wanna get something like this at the end:
I got this errors:
Here is my code:
My view file ("home"):
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 align="center">TABLE:Study</h2>
<input id="busqueda_tabla" type="text">
<table class="table table-hover" align="center" border="1" cellspacing="0" cellpadding="0" width="700" id="tabla_busqueda">
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
<th>Action</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['user']."</td>
<td>".$record['subject']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
<td align='center'>
<button type='button' class='btn btn-primary'>EDITAR</button></a> |
<button type='button' class='btn btn-danger'>BORRAR</button></a>
</tr>";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Here is my Controller file ("Home"):
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Crudmodel");
}
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
$data[$key]['user_id'] = $user[0]['username'];
$data[$key]['subject_id'] = $subject[0]['name'];
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}
}
?>
And my Model file ("Crudmodel"):
<?php
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM Study");
$result = $query->result_array();
return $result;
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM Users WHERE id = $name ");
$result = $query->result_array();
return $result;
}
function getSubName($subject)
{
$query= $this->db->query("SELECT name FROM Subjects WHERE id = $subject ");
$result = $query->result_array();
return $result;
}
}
?>
Hope you can help me :/
Iam changed your query to join query, Simply change your code to below
public function index(){
# get all data in Study table
$query = $this->db->query("SELECT sd.user_id as id,sd.grade as grade,sd.date as date,sd.subject_id as subject,ur.username as user FROM Study as sd,Users as ur,Subjects as sb WHERE ur.id=sd.user_id and sb.id=sd.subject_id");
$result = $query->result_array();
$data['records'] = $result;
$this->load->view('home', $data);
}
and now run the code
Undefined indexes and trying to get property non-object more or less means the same thing which is you are not getting proper data or the variables or indexes you are trying to get are not initialized or undefined and cause of this can be error in query or blank data return by query you are running.
i would like to request you to pull your query data like this
$check = $this->db->query("SELECT * FROM SOMETHING AND YOUR CONDITION AND STUFF HERE");
if($check->num_rows()>0){
$result = $check->result();
return $result;
}else{
return false; // or anything you want.
}
let say this query function is stored in model and you are calling your model like this
$someVariable = $this->model_name->function();
if($someVariable!==FALSE){
// handle
}else
{
// handle
}
in the end, not sure why, but i also counter problems with double quotes sometime, YES I KNOW.. variable inside double quotes work, I'm just saying sometime... at least it happens with me, so i would like to request last thing. try debugging your query like this, currently you have
"SELECT * FROM TABLE WHERE THIS = $THAT"
Change this to
"SELECT * FROM TABLE WHERE THIS = '".$THAT."'"
I hope it will work out for you!.
EDITED:
(Sorry that i failed to show example from your own code)
Your Model file
<?php
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM Study");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM Users WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getSubName($subject)
{
$query= $this->db->query("SELECT name FROM Subjects WHERE id = $subject ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function CombineResults($subject, $name){
// you can also use this
$query = $this->db->query("SELECT sub.name, user.username FROM Subjects sub, Users user WHERE sub.id=$subject AND user.id = $name");
if($query->num_rows()>0){
return $query->result();
}else{
return "";
// or anything you can use as error handler
}
}
}
?>
Your controller file
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
// we have condition on this model method/function we can validate
// response comming from this method and add handler just like we did
// for queries. your main problem can be this
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
if(!empty($user[0]['username'])){
$data[$key]['user_id'] = $user[0]['username'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler
}
if(!empty($subject[0]['name'])){
$data[$key]['subject_id'] = $subject[0]['name'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]["subject_id"] = "";
// or anything you can use as error handler
}
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}

How to get a specific array value on a passed array in codeigniter?

I have this controller where all the available users and its respective information are passed in the view through an array:
function view() {
$data = array();
if($query = $this->m_user->get_user()) {
$data['user'] = $query;
}
$this->load->view('v_view_user', $data);
}
In my view I used this method (the norm) to view all that was passed:
<?php echo "user_name here" ?>
<?php if(isset($user)) : foreach ($user as $row) :
echo $row->user_name;
end foreach;
end if;
?>
What I want to do is to print a specific index (the name to be specific) before the code given above.
For the model:
function get_employees() {
$query = $this->db->get('user');
return $query->result();
}
By the way, the array contains user_id, user_name, user_family_name, ..., [and other more].
Your help will be highly appreciated.
$query->result(); will return the array of objects. So you can get user_name as below:
<?php if(isset($user)) : foreach ($user as $row) :
echo $row->user_name;
end foreach;
end if;
?>
EDIT: After question updated with my answer
you can use below code to get outside the loop:
echo $user[0]->user_name; // returns the first user_name

Join does not work

I have write a function using SQL join but i do not know why it does not work
this is a model
public function get_contract_user($user_id)
{
$this->db->select('contracts.*');
$this->db->from('contracts');
$this->db->join('link', 'contracts.contract_id = link.contracts_contract_id');
$this->db->where('link.users_user_id', $user_id);
$query = $this->db->get();
return $query->result();
}
this is the app
$data['query'] = $this->admin_model->get_contract_user($contract_id);
this is a view
foreach($query as $row)
{
echo $row->contract_code;
echo $row->contract_num;
echo $row->contract_start;
echo $row->contract_end;
}
You defined method get_contract_user, but you are using get_contract in provided code.
You should be getting an error concerning undefined function/method.

Php Display While Loop From Function

I have a question regarding displaying the contents of a function, this function displaying a while loop.
Here is a function within my model:
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$result = '';
while($row = mysqli_fetch_array($stmt))
{
$result .= '<div>';
$result .= $row['name'];
$result .= '</div>';
}
$this->BEAR->Template->setData('loop', $result, FALSE);
}
This is my Controller:
$BEAR->Webprofile->get_results(Template->getData('id'));
And this is my view:
<?php echo $this->getData('loop');?>
This displays the Loop within my view with no problem. But what I wish for is not to have any HTMl within my Model, Is there anyway of doing this (As this can cause a large amount of HTML in my Model). Maybe a way I can set the data within the Model and then get the data within my view.
I tried setting within the Model functions while loop individually like the following:
while($row = mysqli_fetch_array($stmt))
{
$this->BEAR->Template->setData('name', $row['name']);
$this->BEAR->Template->setData('name', $row['age']);
}
Then call the function in the Controller and call each setData, but this only displayed the first result not the full while loop of contents.
Therefore I wish to display all the contents of my while loop in my view (with HTML) but wish my function to just be getting and setting the Data. Can this be done? Any thoughts or guidance would be appreciated.
You need to apply some discipline to your MVC. Your models need to return raw data. It should return only objects or arrays of data. The key is consistency.
Your views need to include all the code to add your html formatting. Having a view that simply calls a model function you wrote that spits out a div or an ordered list, makes the entire concept of the view useless. Your views should provide all the HTML code.
Since you're using PHP, you can easily drop in and out of HTML.
Start with something like this in your model:
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$results = array();
while($row = mysqli_fetch_array($stmt))
{
$results[] = $row['name'];
}
return results;
}
From there, you should be able to figure out that your controller should call this function, and pass the $results into your view/template along with the specific view file for rendering.
function get_results($id)
{
$stmt = "select * where ... "
$stmt = $this->BEAR->Database->query($stmt);
$result = '';
$result = mysqli_fetch_array($stmt);
return $result;
}
Then in your controller:
$this->BEAR->Template->setData('loop', $model->get_results($id), FALSE);
Then in your template
foreach($rows as $row){
....do something with each row
}
full example of how to get the data from the model and then pass to the template
class MyController {
function controller_showResults(){
$model = new Model();
$results = $model->get_results($_GET['id']);
$this->BEAR->Template->setData('loop', $results, FALSE);
}
}
Now the view assuming that the first argument to setData in template is a variable passed to the view and that variable is $results
<?php foreach($loop as $l): ?>
<div><?php echo $l['name'] ?></div>
<?php endforeach; ?>

Categories