Code Igniter, array printing in view - php

This is my model
<?php
class home_model extends CI_Model {
function login()
{
$q = $this->db->query('SELECT * FROM users');
$count = $q->num_rows();
if ($count > 0)
{
foreach ($q->result() as $row)
{
$data[]['username'] = $row->username;
$data[]['email'] = $row->email;
$data[]['sex'] = $row->sex;
$data[]['dob'] = $row->dob;
$data[]['mobile'] = $row->mobile;
}
return $data;
}
?>
This is my controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class home extends CI_Controller
{
public function index()
{
$this->load->model('home_model');
$data['records'] = $this->home_model->login();
$this->load->view('home', $data);
}
}
I am only able to print_r and that is not how i want it, how will i echo this? I don't know what format I should use in my echo,
echo($records[0]);
This format is what I tried but it returns the error
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/home.php
Line Number: 4 Array
How should I code my view?

first of all your login function is need to corrected as per codeigniter.
function login() {
$q = $this->db->query('SELECT * FROM users');
$count = $q->num_rows();
if ($count > 0) {
return $q->result_array();
}
it will provide an array as you required.
then to use in views, you need to use it following.
suppose you want to echo first user name
echo $records[0]['username'];
Here $records[0] is an array and hence you need to use as above mention and similarly for other field.

Use following process
Your Modal
function login()
{
$q = $this->db->query('SELECT * FROM users');
$count = $q->num_rows();
if ($count > 0)
{
return $q->result();
}
}
?>
No change for controller
On View
foreach ($records as $row)
{
$username = $row->username;
$email = $row->email;
$sex = $row->sex;
$dob = $row->dob;
$mobile = $row->mobile;
}

In your views
foreach($records as $users)
{
echo $users['username'];
}

Use the builtin function print_r() and provide the array is an argument

Related

Invalid argument supplied Codeigniter

My program is not working properly, i do not know what should i do :S
I got this error message:
Take a look at this:
Here is my code:
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
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);
}
}
?>
Crudmodel:
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
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 usuarios WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
Dont know what to do now :(
Hope you can help me :S
The problem is in the model. You only return something inside the else. Easy fix, move the return.
You should probably return an empty array if there are no rows. Then the foreach will still have something to work with - even if it is empty. foreach will choke if given something that cannot be used in a loop - a string for instance.
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = array();
}
return $result;
}

Undefined variable and Invalid argument supplied for foreach()

i'm trying to learn codeigniter and i have problem here. There was an error Undefined variable and Invalid argument supplied for foreach() on view. here is the code :
Model (Model_Users.php) :
class Model_users extends CI_Model {
function __construct() {
parent::__construct();
}
function getFirstNames(){
$query = $this->db->query('SELECT firstname FROM users');
if($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getUsers(){
$query = $this->db->query('SELECT * FROM users');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
}
Controller (welcome.php) :
class Welcome extends CI_Controller {
public function index()
{
$this->home();
}
public function home()
{
$this->load->model('model_users');
$data['title'] = 'MVC Cool Title';
$data['page_header']='Intro to MVC Design';
$data['firstnames'] = $this->model_users->getFirstNames();
$data['users'] = $this->model_users->getUsers();
$this->load->view('welcome_message',$data);
}
}
View (Welcome_message.php) :
<div id="container">
<h1><?php echo $page_header ?></h1>
<div id="body">
<?php
foreach ($firstnames as $object) {
echo $object->firstname .'<br/>';
}
echo '<br/><hr/><br/>';
foreach ($users as $object){
echo $object->firstname . '\'s email address is'. $object->email . '<br/>';
}
?>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
Please help me what is wrong with my code ?
First check value return any value or not write this code in controller
use
var_dump($firstnames);
and
var_dump($users);
I think no data return from model
check any data in table
Thanks
You can eliminate the error by using return []; instead of return null; instead of checking for that case in every foreach call, because it appears that your user table might be empty based on the code provided.
Modify your model functions like below
function getFirstNames(){
$query = $this->db->get('users')->row()->firstname;
if($query->num_rows() > 0) {
return $query->result_array();
} else {
return NULL;
}
}
function getUsers(){
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return NULL;
}
}
hope this will help

Call to a member function num_rows() on boolean in PHP

I am getting the below error on my code,
Call to a member function num_rows() on boolean in C:\xampp\htdocs\codeigniter\application\controllers\go.php on line 15
Code:
<?php if (!defined('BASEPATH')) {
exit('No direct script access
allowed');
}
class Go extends MY_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('string');
}
public function index()
{
if (!$this->uri->segment(1)) {
redirect(base_url());
} else {
$url_code = $this->uri->segment(1);
$this->load->model('Urls_model');
$query = $this->Urls_model->fetch_url($url_code);
if ($query->num_rows() == 1) {
foreach ($query->result() as $row) {
$url_address = $row->url_address;
}
redirect(prep_url($url_address));
} else {
$page_data = array(
'success_fail' => NULL,
'encoded_url' => FALSE,
);
$this->load->view('common/header');
$this->load->view('nav/top_nav');
$this->load->view('create/create', $page_data);
$this->load->view('common/footer');
}
}
}
}
#ahmed is correct that db code belongs in the model but the problem you're having is most likely from a db error.
Besides fixing the problem, the workaround is this.
if ($query->num_rows() == 1) {
should be changed to
if ($query && $query->num_rows() == 1) {
I would put an else in there to dump the $this-db->error() to the error_log so you can see what the problem is.
You should call the 'num_rows()' inside the Model, not the Controller, for this function is used often after the get() method:
//Model function:
$query = $this->db->get();
$data = Array();
if($query->num_rows()){
//Work with data:
foreach($query->result_array() AS $row){
$data[] = $row;
}
}
return $data;
I suppose if you want to use the num_rows inside the controller, you should return the query AS a result like this:
$query = $this->db->get();
return $query;
$data = [];
$this->db->where('', 0);
$query = $this->db->get('');
if ($query->num_rows()>0)
{
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
First of all check that values come from database. if values come from table then put greater than 0 . if your value exist then query run forword. i thank this is help for you
This is caused by buggy Active Records in CI that adds an extra WHERE clause causing ambiguous column names and similar.
Try to get the actual query with $this->db->last_query(); and it will be instantly clear why $query is not an object.

view in codeigniter passing of array not working

So my problem is that the values from this specific id won't print. I really don't know what's the problem since there is no error. please help guys. Still a newbie at using this framework. thanks!
controller:
public function teacher(){
$this->load->model('model_teacher');
$id = $this->input->post('idnum');
$data['result'] = $this->model_teacher->scoreboard($id);
$this->load->view('teacher/teacher', $data);
}
model:
class Model_teacher extends CI_Model {
public function scoreboard($id) {
//$this->db->where('login_id', $this->input->post('idnum'));
$query = $this->db->query("SELECT * FROM teacher WHERE login_id = '".$id."'");
return $query->result();
}
}
view:
<?php
foreach ($result as $a) {
echo $a['login_id'];
echo $a['lname'];
echo $a['mname'];
echo $a['fname'];
}
?>
Alternative to Ghost's answer:
To keep you model the same you would just need to change your view file from:
foreach ($result as $a) {
echo $a['login_id'];
echo $a['lname'];
echo $a['mname'];
echo $a['fname'];
}
To:
foreach ($result as $a) {
echo $a->login_id;
echo $a->lname;
echo $a->mname;
echo $a->fname;
}
This is because result() with the DB driver returns an array of Objects where as result_array() returns an array of arrays.
Hope this helps!

Can't access global variable in PHP codeigniter Model class.

I have a class in Codeigniter which extends CI_Model.
I have declared a global array $data, but I can't access this array from my functions which i want to push some items.
that shows
A PHP Error was encountered Message: Undefined variable: data
and Fatal error: Cannot access empty property in /api/system/core/Model.php on line 51
code for class:
class Subscription_collection_model extends CI_Model {
public $data=array();
/*
|-----------------------------------------
| Constructor
|-----------------------------------------
*/
function __construct() {
parent::__construct();
}
function get() {
$this->db->select('family.house_name,family.id,family_grade.amount');
$this->db->from('family');
$this->db->join('family_grade','family_grade.id = family.family_grade_id');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$this->findBalance($row->id);
}
}
return $data;
}
function findBalance($id) {
$this->db->where('family_id', $id);
$this->db->select_sum('collecting_amount');
$query = $this->db->get('subscription_collection');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
array_push($this->$data,$row->collecting_amount);
}
}
}
}
you got a typo there. you want to call $this->data not $this->$data.
the latter would assume, you wanna call a dynamic variable on the instance.
$prop = 'myProperty';
$this->$prop = 'test';
is the same as
$this->myProperty = 'test';
How about:
return $this->data;

Categories