I have been pulling my hair out for too long looking at this error. I am using Codeigniter 2 and have created MY_Controller class to load a few settings into my session data.
Which you can see below:
class MY_Controller extends CI_Controller {
protected $ajax = 0;
public function __construct() {
parent::__construct();
$this->load->model('settings_model');
//is the session user agent set
if ($this->session->userdata('browser') == false)
{
$this->load->library('user_agent');
$this->session->set_userdata(array(
'browser' => $this->agent->browser(),
'browser_version' => $this->agent->version(),
'is_mobile' => $this->agent->is_mobile() ? 1 : 0
));
}
//is the settings loaded
if ($this->session->userdata('league_name') == false)
{
$this->Settings_model->get_general_settings();
}
//get the menu if we need to
//if ($this->session->userdata('menu') == false)
//$this->Settings_model->get_menu_items();
//set the main part of the title
$this->set_title($this->session->userdata('league_name'));
//get that referring url
$this->session->set_userdata('refered_from', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : base_url());
//ajax request
$this->ajax = isset($_GET['ajax']) ? 1 : 0;
}
}
Where I am running into the problem is I keep getting this error:
Fatal error: Call to a member function get_general_settings() on a non-object in C:\xampp\htdocs\osmdev\application\controllers\welcome.php on line 12
Here is the Settings_model.php file that I am loading, yes it is in my application/models folder:
class Settings_model extends CI_Model
{
// Call the Model constructor
function __construct() {
parent::__construct();
}
//get the general settings
function get_general_settings() {
$query = "SELECT setting_id, variable, value FROM settings WHERE non_session = 0";
$result = $this->db->query($query);
foreach ($result->result_array() as $row)
$this->session->set_userdata($row['variable'], stripslashes($row['value']));
}
//get all the settings we have
function get_all_settings() {
$query = "SELECT setting_id, variable, value FROM settings";
$result = $this->db->query($query);
foreach ($result->result_array() as $row)
$this->session->set_userdata($row['variable'], stripslashes($row['value']));
}
//get a specfic setting variable
function get_specific_setting($var) {
$query = "SELECT setting_id, variable, value FROM settings WHERE variable = '".$var;
$result = $this->db->query($query);
foreach ($result->result_array() as $row)
$this->session->set_userdata($row['variable'], stripslashes($row['value']));
}
//get a specific type of setting
function get_type_setting($type) {
$query = "SELECT setting_id, variable, value FROM settings WHERE action = '".$type;
$result = $this->db->query($query);
foreach ($result->result_array() as $row)
$this->session->set_userdata($row['variable'], stripslashes($row['value']));
}
//get all the menu items
function get_menu_items($type=0) {
$query = "SELECT menu_id, title, menu_url, parent_id, level, function_used, perm_id, icon FROM menu WHERE active = 1 AND is_admin_menu = '".$type;
$result = $this->db->query($query);
foreach ($result->result_array() as $row)
$items[$row['menu_id']] = $row;
$this->session->set_userdata('menu', $items);
}
}
I am trying to call the get_general_settings function. Can anyone see what I am doing wrong?
You could try to setup the model to store $row into an array and then return the array.
Your model:
function get_general_settings() {
$rows = array();
$query = "SELECT setting_id, variable, value FROM settings WHERE non_session = 0";
$result = $this->db->query($query);
foreach ($result->result_array() as $row)
$variable = $row['variable'];
$value = stripslashes($row['value']);
$rows[] = $variable[$value];
return $rows[]
Your controller:
//is the settings loaded
if ($this->session->userdata('league_name') == false)
{
//set userdata to returned $rows[]
$this->session->set_userdata($this->Settings_model->get_general_settings());
}
//echo last_query to test in mysql
$this->db->last_query();
See if that will help solve your problem. I would print_r($this->Settings_model->get_general_settings()); just to see if anything was placed in the array.
Then if nothing is there, echo the last_query to see what it's asking MySQL for and then run that returned query in mysql and see if you get at least one row.
This error can happen when your database user doesn't have select permission for the table you're trying to query. It doesn't make sense, but it happens from time to time.
Related
I'm working on a project. how to calculate comment by id?
example
controler:
public function comments() {
$id_alat = $this->db->where('id_alat');
$com = $this->mcrud->getComent($id_alat);
$com = $this->mcrud->getComent($id_alat);
$data = array (
'com' => $com,
'content' => 'instrument/instrument');
$this->load->view('layouts/wrapper', $data);
}
models:
public function getComent($id_alat) {
$sql = "SELECT count (*) as num FROM WHERE tbcoment $id_alat tbcoment.id_alat = {}";
$this->db->query($sql);
}
view:
comments: <?php echo $com; ?>
Use following code for model
Your Model
public function getComent($id_alat)
{
$sql = "SELECT count (*) as num FROM WHERE tbcoment.id_alat = '$id_alat'";
$res=$this->db->query($sql)->row_object();
return $res->num;
}
Note: Don't use spaces inside php tags and variables.
Ex01: $ id_alat should come $id_alat
Ex02: $ this-> mcrud-> getComent ($ id_alat); should come $this->mcrud-> getComent($id_alat);
Code Example
In controller
function comments () {
$id_alat = '';//Asign data to here
$data['com'] = $this->Model_name->getComent($id_alat);
$data['content'] = 'instrument / instrument';
$this->load->view ('layouts/wrapper', $data);
}
In Model
function getComent($id_alat) {
$query =$this->db->query("SELECT * FROM table_name WHERE tbcoment='$id_alat'");//cahnge table name, and argument that you want
$result = $query->result_array();
$count = count($result);
return $count;
}
In view
comments: <?php echo $com; ?>
you can also use this code:
$this->db->where('id',$id)
->from('table_name')
->count_all_results();
this can be used either on MVC(Model, View, Controller);
you can find this code on the user guide
I'm getting a weird error when trying to call a model method from one of my controllers say problem.php, all the values are fine but $this->db->get(); returns false, even the query returned from $this->db->last_query() is fine.
And the main issue is, when i pass the same values from another controller say test.php, everything works fine. Is this some caching issue?
Heres my code for the model
function how_many_left($product_id)
{
var_dump($product_id);
$sql="select * from invite where product_id=".$product_id." and accepted = 1";
echo "<br/>Product id:".$product_id."<br/>";
$query = $this->db->query($sql);
echo $this->db->last_query();
$invites = $query->num_rows();
echo $invites;
$this->db->select('quantity');
$this->db->where('product_id', $product_id);
$query2 = $this->db->get_where('product_inventory');
$quantity = 0;
foreach ($query2->result() as $row)
{
$quantity = $row->quantity;
}
$inventory = $quantity - $invites;
return ($inventory);
}
the call from the controller which is not working
foreach ($user_list as $product_id => $value) {
if (!isset($product_wise_invites[$product_id]))
{
$product_wise_invites[$product_id] = array();
}
if($this->debug_mode())
{
echo "Product id to get error on :<br/>";
var_dump($product_id);
}
$invites_left = $this->Product->how_many_left($product_id);
output of the controller not working
int(1349375633)
select * from invite where product_id=1349375633 and accepted = 1
Call to a member function num_rows() on a non-object in /opt/bitnami/apache2/htdocs/application/models/internal.php on line 1135
the call from the working controller
function invite_server_test()
{
$product_id=1349375633;
$this->Product->how_many_left($product_id);
}
The output of the working controller:
int(1349375633)
Product id:1349375633
select * from invite where product_id=1349375633 and accepted = 1
0
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.
I have successfully implemented the pagination box in a component front end listing template. however, when i try to set the limit of listing items, it won't work, i wonder what is missed out.
in the model
var $_total = null;
/**
* Pagination object
* #var object
*/
var $_pagination = null;
function __construct(){
parent::__construct();
$mainframe = JFactory::getApplication();
// Get pagination request variables
$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function _buildQuery(){
$query = ' SELECT * '
. ' FROM #__event '
.'Where published = 1'
;
return $query;
}
function getData() {
// if data hasn't already been obtained, load it
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
function getTotal(){
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getPagination(){
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
in the views/view.html.php (full version of this document)
class EventViewListing extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
$model= & JModelLegacy::getInstance('Event','EventModel');
$pagination = $model->getPagination();
$this->assignRef('pagination', $pagination);
$JDoc =& JFactory::getDocument();
$db = JFactory::getDBO();
$sql = "SELECT * FROM #__event WHERE published = 1 ORDER BY id DESC";
$db->setQuery($sql);
$rows = $db->loadObjectList();
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$rows2 = $db->loadObjectList();
$this->assignRef('rows',$rows);
$this->assignRef('rows2',$rows2);
// $JDoc->setTitle(' ');
// Display the view
parent::display($tpl);
}
}
in the default.php
<form action="<?php echo JRoute::_('index.php?option=com_event'); ?>" method="post" name="adminForm">
<?php echo $this->pagination->getListFooter(); ?>
<input type="submit" name="submit" value="GO!" />
</form>
hope someone could help
thank you!
The limits need to also be used in the queries to limit the number of records that are displayed to the page that you are on. Typically this can be done in the setQuery function, which allows a second and third parameter to set the limit size and start position.
$sql = "SELECT * FROM #__event WHERE published = 1 ORDER BY id DESC";
$db->setQuery($sql, $model->getState('limitstart'), $model->getState('limit'));
$rows = $db->loadObjectList();
// I'm not sure what this query is for, but since it probably isn't supposed to be limited to a set number of items, don't update it's setQuery call.
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$rows2 = $db->loadObjectList();
I think that fixes the problem that you are having.
That being said, you have a host of minor issues that are making this a lot harder for you or just using outdated practices:
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
Using JRequest::getVar() is deprecated and likely to be removed in future versions of Joomla. Instead use this:
$limitstart = JFactory::getApplication()->input->get('limitstart', 0, 'INT');
Note that the parameters have changed slightly. This uses a different class to parse input to the application.
$this->assignRef('rows',$rows);
The above is unnecessary anymore (was only needed back in PHP4 from what I understand). Instead just do $this->rows = $rows;
Finally, the big overall issue is that you aren't really using Joomla's help.
Your model should just be extending from the class JModelList since you are trying to create a list of events. If you extend from that class and name your functions properly, Joomla will do most of the work:
Rename _buildQuery to getListQuery.
Pretty much delete every other function in your model, since Joomla has all of them in JModelList doing basically the same things.
Update your view to this:
class EventViewListing extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
$JDoc = JFactory::getDocument();
$db = JFactory::getDBO();
$this->pagination = $this->get('Pagination');
$this->rows = $this->get('Items');
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$this->rows2 = $db->loadObjectList();
// $JDoc->setTitle(' ');
// Display the view
parent::display($tpl);
}
}
$this->get() in the JViewLegacy class will call the model (with the same name as the view) and run the method of that model that starts with get followed by whatever word is in the function, so $this->get('Pagination') calls the models getPagination function.
And again, all of the functions that you are adding in the model exist already in libraries/legacy/model/list.php, so just use them!
I have the following code on my site:
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
$smarty->assign('results', $results);
}
It works without any problems, but now I wanted to put most of this in my database class to work more object oriented. But I have some problems returning the array. I have done this
$statusMessage = $db->getStatusMessages();
var_dump($statusMessage);
The function:
function getStatusMessage(){
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
}
return $results;
}
But this just tells me, that my array is null. so there have to be an problem with my returning. How do I do it correctly?
My database entries are statusID, posterID, statusMessage, dateTime, sumRating and sumVotes.
And what do I do if I want to also return an entry of another table? Like, I have the givenName and familyName of the poster (posterID) on another table. How do I also return this data?
Okay I got it. First of all, I made the mistake, that I - as #slugonamission said - that I made a spelling mistake in the function name. Then, I changed my forloop in the home.php from
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage[$i]);
}
to this, because the [$i] at the end made the forloop only use the last entry of the database and from that only the first letter.
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage);
}
Now what I'm working on is how to get data from other tables, too.
function getStatusMessage(){
global $db; // this is what you actually need to make function work
$sql = "SElECT s.*, username FROM statusmessages s JOIN users u ON posterID.=u.id";
$stm = $db->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
note that you have to use JOIN to get associated info
You have to parse your $db variable to your function:
function my_function() {
global $db;
// some code
}
or to use it like this:
class myClass {
private $db;
public function __construct() {
$this->db = new MySQLi("host","user","pass","db");
}
public function my_function() {
$my_db_query = $this->db->query('query');
}
}