Trying to get my data to display on the view- codeigniter - codeigniter

From my controller, I am able to get the session date to display on my view, I however an missing something in the syntax when it comes to displaying the data from my table. i.e $data['modelData']. How do I do that?
Controller:
function validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required|md5');
if ($this->form_validation->run() == FALSE )
{
$this->load->view('login_form');
//return false;
}
else{
$this->load->model('login_model');
$email = $this->input->post('email');
$password = $this->input->post('password');
//echo $email;
// echo $password;
$result = $this->login_model->match_login($email, $password);
if ($result ==false) {
echo "Invalid Cardinals";
}
else
{
$session = array(
'id'=>$result[0]['id'],
'email'=>$this->input->post('email'),
'is_logged_in'=> 1
);
if (!$this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
else {
echo "Error in session";
}
}
}
}
Model
class Login_model extends CI_Model{
//client..model
public function match_login($email, $password){
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get('user');
$result = $query->result_array();
if (empty($result))
{
return false;
}
else
{
return $result;
}
}
}

Try this
In Controller
if (!$this->session->set_userdata($session)) { # Changed
echo "Error in session";
}
else {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
In View
// retrieving modelData
foreach ($modelData as $modelItem) {
echo "Model ID is ".$modelItem['id'];
}
// retrieving sessionData
foreach ($sessionData as $sessionitem) {
echo "Session ID is ".$sessionitem['id'];
echo "Session Email is ".$sessionitem['email'];
}

Replace:
if (!$this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
with
if ($this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
Explantion:
You could not get data from the table since the set_userdata function returned true therefore the control statement ignored the statements if block.

Related

Codeigniter select 2 users and send them emails

When I send email using the following code, it works fine.
public function select() {
$this->load->library('email', array('mailtype' => 'html'));
$this->email->from('test#test.com','abc');
$this->email->to('test1#test.com');
$this->email->subject('test subject');
$message = "Hello";
$this->email->message($message);
if($this->email->send()) {
$data["msg"] = "Email has been successfully sent.";
$this->load->view("view_test", $data);
}
else {
$data["msg"] = "Email sending failed.";
$this->load->view("view_test", $data);
}
}
But when I want to select 2 users by id and then send them emails it does not work. Could you please check my code below and help me to find my mistake.
Model
public function did_select() {
$this->db->select('email, name');
$this->db->from('users');
$this->db->where('user_id', 5);
$this->db->where('user_id', 11);
$query = $this->db->get();
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
Controller:
public function select() {
if ($this->model_admin->did_select()) {
foreach ($query->result_array() as $row) {
$name = $row['name'];
$email = $row['email'];
$this->load->library('email', array('mailtype' => 'html'));
$this->email->from('test#test.com','abc');
$this->email->to($email);
$this->email->subject($name.'test subject');
$message = "Hello";
$this->email->message($message);
if($this->email->send()) {
$data["msg"] = "Email has been sucessfully sent.";
$this->load->view("view_test", $data);
}
else {
$data["msg"] = "Email sending failed.";
$this->load->view("view_test", $data);
}
}
}
}
The problem is this two lines
$this->db->where('user_id', 5);
$this->db->where('user_id', 11);
This produces query like
Where user_id=5 and user_id=11
which is not you want. So you should replace the second line with
$this->db->or_where('user_id', 11);
Also maybe your should remove view loading outside the foreach loop.
You already have returned result_array in model, so no need to double it. In controller try next:
if ($this->model_admin->did_select())
{
$mails = $this->model_admin->did_select();
foreach ($mails as $row)
{

How to pass a message from model to controller codeigniter?

I want to pass a message variable in some conditions to controller from model in codeigniter. But when i am doing this it is printing only "No" everytime.
Model is
public function add_city() {
/* Storing form data into an array */
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
And Controller is
public function addingCity() {
$this->add_model->add_city();
var_dump($msg);
//redirect("/city");
}
Try This also
public function add_city() {
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
On controller redirect message with get method -
public function addingCity() {
$msg = $this->add_model->add_city();
redirect("/city?msg=".$msg);
}
And finally print this message on view page
echo $this->input->get('msg');
You need to assign value to $msg in your controller
public function addingCity() {
$msg=$this->add_model->add_city();// assign
var_dump($msg);
//redirect("/city");
}
Try this
public function add_city() {
$city_name = $this->input->post('city');
$city_overview = $this->input->post('overview');
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
$result = $query->result_array()
$count = count($result);
if(empty($count))
{
$msg = "No";
return $msg;
}
else{
$data = array(
'city_name'=>$this->input->post('city'),
'city_overview'=>$this->input->post('overview') );
$this->db->insert('city_tbl', $data);
$msg = "Yes";
return $msg;
}
}
In Controller
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;
}
To pass data to view
public function addingCity() {
$data['msg'] = $this->add_model->add_city();
$this->load->view("filename", $data); # ex $this->load->view("index", $data);
}
Error is in your controller function
Try with this code
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;die;
//redirect("/city");
}

Best Practice: Models and Controllers

I would like to get your MVC experience on the following:
I have a table where I say which user_id is in which group_id and a second table where I say which user_id has which user_name.
Now I want a function to which I pass a group_id and it gives me all user_names in the group.
The question is, what does the Controller do and what the Model:
Controller calls a Model (get_user_ids_from_group) that returns the user ids and then the controler calls different model (get_user_name_by_id) to return the usernames.
A controller calls a Model (`get_user_names_from_group) and the model internally gets first the user ids and then the user names.
I understand that the first way is more MVC strict. But how strict would you be in a case like this? Right now I am always being very strict.
As a result my model functions have always just two lines (query and return) and my controller are bigger. So to make controller and model size more equal the second option would be possible.
Actually, it has nothing to do with MVC, as CodeIgniter doesn't implement MVC, but a sort of MVP.
However, if you're using RDBMS such as MySQL, you could JOIN these two table (within the Model) and fetch the result (within the Controller) as I suggested in a similar topic on SO.
application/models/user.php
class User extends CI_Model
{
public function get_users_by_group($group_id)
{
$this->db->select('*')->from('groups');
// While group_id and user_id have a N:1 relation
$this->db->where('group_id', $group_id);
$this->db->join('users', 'users.user_id = groups.user_id');
$query=$this->db->get();
return $query->result_array();
}
}
Then fetch and pass the result within the Controller:
application/controllers/users.php
class Users extends CI_Controller
{
public function view($group_id)
{
$this->load->model('user');
// Fetch the result from the database
$data['users'] = $this->user->get_users_by_group($group_id);
// Pass the result to the view
$this->load->view('users_view', $data);
}
}
In MVC model should not be only use for storing and getting the data but also it should contain the business logic.
Controller - Should take input communicate with model and view
Model - Should contain business logic and data store
View - Only for Output
So its like Input -> Process -> Output
Also its depend on you where to put what and you should have a balance code on controller and model, Not write everything in controller or in model
In you case I think you should uses get_user_names_from_group and just pass the group name and make a join query between two table. And when you define your function in the model its give you the option to reuse the function again in case you need same thing on next controller.
Common model example:
<?php
class Common_model extends CI_Model {
function get_entry_by_data($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '') {
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function get_entry_by_data_in($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '',$in_column='',$in_data=''){
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
if (!empty($in_data) and !empty($in_column)) {
$this->db->where_in($in_column,$in_data);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function getAllRecords($table, $orderby_field = '', $orderby_val = '', $where_field = '', $where_val = '', $select = '', $limit = '', $limit_val = '') {
if (!empty($limit)) {
$offset = (empty($limit_val)) ? '0' : $limit_val;
$this->db->limit($limit, $offset);
}
if (!empty($select)) {
$this->db->select($select);
}
if ($orderby_field)
$this->db->order_by($orderby_field, $orderby_val);
if ($where_field)
$this->db->where($where_field, $where_val);
$query = $this->db->get($table);
//return $query->num_rows;
//echo $this->db->last_query();
if ($query->num_rows > 0) {
return $query->result_array();
}
}
function alldata($table) {
$query = $this->db->get($table);
return $query->result_array();
}
function alldata_count($table, $where) {
$query = $this->db->get_where($table, $where);
return $query->num_rows();
}
function insert_entry($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
function update_entry($table_name, $data, $where) {
return $this->db->update($table_name, $data, $where);
}
public function get_data_by_join($table, $table2, $where, $table1_column, $table2_column, $limit = '', $order_column = '', $order_by = 'DESC', $select_columns = '', $is_single_record = false, $group_by = '', $join_by = '', $offset = '') {
if (!empty($select_columns)) {
$this->db->select($select_columns);
} else {
$this->db->select('*');
}
$this->db->from($table);
$this->db->join($table2, $table . '.' . $table1_column . '=' . $table2 . '.' . $table2_column, $join_by);
$this->db->where($where);
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
} else {
$this->db->limit($limit);
}
}
if (!empty($order_column)) {
$this->db->order_by($order_column, $order_by);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
if ($is_single_record) {
$rs = $query->result_array();
return $rs[0];
} else {
return $query->result_array();
}
} else {
return false;
}
}
function DeleteRecord($table_name, $where) {
return $this->db->delete($table_name, $where);
}
function managerecord() {
$count = 1;
$where = array('channel_id' => 8,
'field_id_12 !=' => '');
$this->db->where($where);
$query = $this->db->get('channel_data');
$data = $query->result_array();
foreach ($data as $value) {
$id = $value['field_id_12'];
$update = array('telephone' => $value['field_id_53'],
'about' => $value['field_id_54'],
'license' => $value['field_id_18'],
'broker' => $value['field_id_19'],
'preferred' => 'yes');
$this->db->update('members', $update, array('member_id' => $id));
}
echo "done1";
}
public function get_content_landing_page($table = false, $field = false, $id = false, $id_name = false) {
$this->db->select($field);
$this->db->from($table);
$this->db->where($id_name, $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_field_landing_page($id = false,$fields=false) {
$this->db->select($fields);
$this->db->from('terratino_form_fields_master');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
?>

$this->form_validation->run() not executing

I have an issue in codeignitor form handling it does not execute $this->form_validation->run() on local server. But it does work very fine on live server. I can't find out what is the reason. Here is my controller.
class Login extends CI_Controller
{
function __construct(){
parent::__construct();
}
function removeUser($record_id){
$a = new Alumni();
$a->removeConnections($record_id);
}
function index(){
$redir = isset($_GET['redir'])?$_GET['redir']:'admin';
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('admin');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/login/send_again/');
} else {
//
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
//var_dump($login);
} else {
$login = '';
}
//var_dump($this->input->post("remember"));
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
if ($this->form_validation->run() === false) {
}else{
echo " logged in";// validation ok
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
//echo $loginID;
if ($this->tank_auth->login(
$loginID,
$pass,
$remember,
$data['login_by_username'],
$data['login_by_email'])) { // success
echo "success";
redirect($redir);
} else {
$errors = $this->tank_auth->get_error_message();
//echo "error";
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
.....
Sorry for long code please help me.
I don't see the library getting loaded in your constructor
public function __construct()
{
parent :: __construct();
$this->load->helper('url');
$this->load->helper('cookie');
//load the validation library
$this->load->library('form_validation');
$this->load->library("pagination");
}

codeinighter where field = data from form

I'm trying to match up suppliers from a postcode search:
Model code:
function get_suppliers(){
$this->db->from('suppliers');
$this->db->where('postcode', $data);
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
Controller code:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
echo("postcode entered");
$data['rows'] = $this->site_model->get_suppliers($data);
print_r($data);
}
}
Obviously ignore the printers and echo thats just me bring to see whats going on I'm pretty sure i need to just change the $data in model to something just not sure what(tried heaps of things)
Model:
function get_suppliers($postcode = '*') // <-- Capture the postcode
{
$this->db->from('suppliers');
$this->db->where('postcode', $postcode); // <-- pass it in here
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Controller:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
$data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode
echo("postcode entered: " . $data['postcode'] . "<pre>");
print_r($data);
}
}
In your model:
function get_suppliers($data = ''){
i.e.: You haven't included $data as the argument

Resources