CodeIgniter: Tank Auth, Adding Date of Birth Issues - php

Ok, So I have added a Date of Birth section for the registration process. I have done it in a weird way probably but it is a logical way to do it in my mind so as long as it works I am fine with it. I have created 3 dob fields (dob1, dob2, dob3 - for month, day, year). The problem I have right now is when a user registers the dob values are not stored properly into the database (it seems the values are just random, they show up as random numbers and letters). So I am curious as to what I am doing wrong. Here is what I have done.
EDIT: I have found the problem, but still am looking for a solution. The ordering is mixed up somewhere. My first 2 letters of email go into dob1, first 2 letters of password go into dob2 (dont know if pass or confirm pass), dob1 goes to firstname, dob2 goes to lastnam, username is fine, dob3 goes to email. So I have mixed up the ordering of my array somewhere but I am nut sure where it counts.
EDIT2: I have found my issue. Answer is below.
Register function in controllers/auth.php
function register()
{
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
$this->_show_message($this->lang->line('auth_message_registration_disabled'));
} else {
$use_username = $this->config->item('use_username', 'tank_auth');
if ($use_username) {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_le\
ngth', 'tank_auth').']|alpha_dash');
}
$this->form_validation->set_rules('dob1', 'DOB1', 'trim|required|xss_clean|min_length[2]|max_length[2]');
$this->form_validation->set_rules('dob2', 'DOB2', 'trim|required|xss_clean|min_length[2]|max_length[2]');
$this->form_validation->set_rules('dob3', 'DOB3', 'trim|required|xss_clean|min_length[2]|max_length[4]');
$this->form_validation->set_rules('firstname', 'First Name', 'trim|xss_clean|min_length[2]|max_length[50]');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|xss_clean|min_length[2]|max_length[50]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|callback_is_email_domain[ku.edu]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', '\
tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
$captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
$use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
if ($captcha_registration) {
if ($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();
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('dob1'),
$this->form_validation->set_value('dob2'),
$this->form_validation->set_value('dob3'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('dob1'),
$this->form_validation->set_value('dob2'),
$this->form_validation->set_value('dob3'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
if ($captcha_registration) {
if ($use_recaptcha) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$data['use_username'] = $use_username;
$data['captcha_registration'] = $captcha_registration;
$data['use_recaptcha'] = $use_recaptcha;
$this->load->view('auth/register_form', $data);
}
}
Libraries: Tank_Auth.php - I know this is not the whole dob, but calling this function returns nothing, i figure if I can return 1 dob then i can easily return them all. EDIT: I just realized I did not include all of my changes for this file.
else {
$this->ci->session->set_userdata(array(
'user_id' => $user->id,
'dob1' => $user->dob1,
'dob2' => $user->dob2,
'dob3' => $user->dob3,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'username' => $user->username,
'status' => ($user->activated == 1) ? STATUS_ACTIVATED : STATUS_NOT_ACTIVATED,
));
.
.
.
function get_dob()
{
return $this->ci->session->userdata('dob1');
}
.
.
.
function create_user($username, $firstname, $lastname, $email, $password, $email_activation, $dob1, $dob2, $dob3)
{
if ((strlen($username) > 0) AND !$this->ci->users->is_username_available($username)) {
$this->error = array('username' => 'auth_username_in_use');
$hashed_password = $hasher->HashPassword($password);
$data = array(
'firstname' => $firstname,
'lastname' => $lastname,
'dob1' => $dob1,
'dob2' => $dob2,
'dob3' => $dob3,
'username' => $username,
'password' => $hashed_password,
'email' => $email,
Views: registration_form.php
<?php
if ($use_username) {
$username = array(
'name' => 'username',
'id' => 'username',
'value' => set_value('username'),
'maxlength' => $this->config->item('username_max_length', 'tank_auth'),
'size' => 30,
);
}
$email = array(
'name' => 'email',
'id' => 'email',
'value' => set_value('email'),
'maxlength' => 80,
'size' => 30,
);
$firstname = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => set_value('firstname'),
'maxlength' => 50,
'size' => 30,
);
$lastname = array(
'name' => 'lastname',
'id' => 'lastname',
'value' => set_value('lastname'),
'maxlength' => 50,
'size' => 30,
);
$password = array(
'name' => 'password',
'id' => 'password',
'value' => set_value('password'),
'maxlength' => $this->config->item('password_max_length', 'tank_auth'),
'size' => 30,
);
$confirm_password = array(
'name' => 'confirm_password',
'id' => 'confirm_password',
'value' => set_value('confirm_password'),
'maxlength' => $this->config->item('password_max_length', 'tank_auth'),
'size' => 30,
);
$dob1 = array(
'name' => 'dob1',
'id' => 'dob1',
'value' => set_value('dob1'),
'maxlength' => 2,
'size' => 30,
);
$dob2 = array(
'name' => 'dob2',
'id' => 'dob2',
'value' => set_value('dob2'),
'maxlength' => 2,
'size' => 30,
);
$dob3 = array(
'name' => 'dob3',
'id' => 'dob3',
'value' => set_value('dob3'),
'maxlength' => 4,
'size' => 30,
);
$captcha = array(
'name' => 'captcha',
'id' => 'captcha',
'maxlength' => 8,
);
?>
<?php echo form_open($this->uri->uri_string()); ?>
<table>
<?php if ($use_username) { ?>
<tr>
<td><?php echo form_label('Username', $username['id']); ?></td>
<td><?php echo form_input($username); ?></td>
<td style="color: red;"><?php echo form_error($username['name']); ?><?php echo isset($errors[$username['name']])?$errors[$username['name']]:''; ?></td>
</tr>
<?php } ?>
<tr>
<td><?php echo form_label('Email Address', $email['id']); ?></td>
<td><?php echo form_input($email); ?></td>
<td style="color: red;"><?php echo form_error($email['name']); ?><?php echo isset($errors[$email['name']])?$errors[$email['name']]:''; ?></td>
</tr>
<tr>
<td><?php echo form_label('First Name', $firstname['id']); ?></td>
<td><?php echo form_input($firstname); ?></td>
<td style="color: red;"><?php echo form_error($firstname['name']); ?><?php echo isset($errors[$firstname['name']])?$errors[$firstname['name']]:''; ?></td>
</tr>
<tr>
<td><?php echo form_label('Last Name', $lastname['id']); ?></td>
<td><?php echo form_input($lastname); ?></td>
<td style="color: red;"><?php echo form_error($lastname['name']); ?><?php echo isset($errors[$lastname['name']])?$errors[$lastname['name']]:''; ?></td>
</tr>
<tr>
<td><?php echo form_label('Password', $password['id']); ?></td>
<td><?php echo form_password($password); ?></td>
<td style="color: red;"><?php echo form_error($password['name']); ?></td>
</tr>
<tr>
<td><?php echo form_label('Confirm Password', $confirm_password['id']); ?></td>
<td><?php echo form_password($confirm_password); ?></td>
<td style="color: red;"><?php echo form_error($confirm_password['name']); ?></td>
</tr>
<tr>
<td><?php echo form_label('Date of Birth', $dob1['id']); ?></td>
<td><?php echo form_input($dob1); ?></td>
<td><?php echo form_input($dob2); ?></td>
<td><?php echo form_input($dob3); ?></td>
<td style="color: red;"><?php echo form_error($dob1['name']); ?><?php echo isset($errors[$dob1['name']])?$errors[$dob1['name']]:''; ?></td>
</tr>
<?php if ($captcha_registration) {
if ($use_recaptcha) { ?>
<tr>
<td colspan="2">
<div id="recaptcha_image"></div>
</td>
<td>
Get another CAPTCHA
<div class="recaptcha_only_if_image">Get an audio CAPTCHA</div>
<div class="recaptcha_only_if_audio">Get an image CAPTCHA</div>
</td>
</tr>
<tr>
<td>
<div class="recaptcha_only_if_image">Enter the words above</div>
<div class="recaptcha_only_if_audio">Enter the numbers you hear</div>
</td>
<td><input type="text" id="recaptcha_response_field" name="recaptcha_response_field" /></td>
<td style="color: red;"><?php echo form_error('recaptcha_response_field'); ?></td>
<?php echo $recaptcha_html; ?>
</tr>
<?php } else { ?>
<tr>
<td colspan="3">
<p>Enter the code exactly as it appears:</p>
<?php echo $captcha_html; ?>
</td>
</tr>
<tr>
<td><?php echo form_label('Confirmation Code', $captcha['id']); ?></td>
<td><?php echo form_input($captcha); ?></td>
<td style="color: red;"><?php echo form_error($captcha['name']); ?></td>
</tr>
<?php }
} ?>
</table>
<?php echo form_submit('register', 'Register'); ?>
<?php echo form_close(); ?>
**ALSO: If you know how to change the width of the td tag for the registration_form.php then please let me know. I am struggling with that also the simple does not work.

I found where I messed up. I was passing the fields in the wrong order when I called the create_user() function in auth.php. I when into the Tank_Auth.php file and reordered my parameters for that function to match what I was passing in the auth.php.
function create_user($username, $firstname, $lastname, $email, $password, $email_activation, $dob1, $dob2, $dob3)
changed to
function create_user($username, $dob1, $dob2, $dob3, $firstname, $lastname, $email, $password, $email_activation)
This matched the create_user() call i had in the auth.php:
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('dob1'),
$this->form_validation->set_value('dob2'),
$this->form_validation->set_value('dob3'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$email_activation)))

Related

How to bind and output data to codeigniter 3

I have two tables in the database, one stores a list of departments (id and name), and the other a list of doctors, and each doctor is attached to the department, while in the table of doctors, the doctor is attached to the department by department id.
My task is to display a list of doctors in a bootstrap table and so that the department field displays not the department ID but the name of the department, how can I do it?
view
<!-- Table with stripped rows -->
<table class="table datatable" id="example">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Department</th>
<th scope="col">Phone</th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
<?php foreach ($doctors_list as $dl) : ?>
<tr>
<th scope="row"><?= $i; ?></th>
<td><?= $dl['name']; ?></td>
<td><?= $dl['email']; ?></td>
<td><?=$dl['department']; ?> </td>
<td><?= $dl['phone']; ?></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
</tbody>
</table>
controller
public function doctors_list()
{
$data['title'] = 'Dashboard';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['doctors_list'] = $this->db->get_where('user', ['role_id' => 2])->result_array();
$data['department_list'] = $this->db->get('departments')->result_array();
$this->form_validation->set_rules('name', 'Name', 'required|trim');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[user.email]', [
'is_unique' => 'This email has already registered!'
]);
$this->form_validation->set_rules('password1', 'Password', 'required|trim|min_length[3]|matches[password2]', [
'matches' => 'Password dont match!',
'min_length' => 'Password too short!'
]);
$this->form_validation->set_rules('password2', 'Password', 'required|trim|matches[password1]');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar_admin', $data);
$this->load->view('admin/doctors_list', $data);
$this->load->view('templates/footer');
} else {
$email = $this->input->post('email', true);
$role_id = $this->input->post('role_id', true);
$department = $this->input->post('department', true);
$data = [
'name' => htmlspecialchars($this->input->post('name', true)),
'email' => htmlspecialchars($email),
'image' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => htmlspecialchars($role_id),
'department' => htmlspecialchars($department),
'phone' => htmlspecialchars($this->input->post('phone', true)),
'is_active' => 1,
'date_created' => time()
];
$this->db->insert('user', $data);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Congratulation! your account has been created. Please activate your account </div>');
redirect('admin/doctors_list');
}
i am trying to do so
<?=$department_list[$dl['department']]; ?>
but i get an error
After the fix
Controller
public function doctors_list()
{
$data['title'] = 'Dashboard';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['doctors_list'] = $this->db->get_where('user', ['role_id' => 2])->result_array();
$departments = $this->db->get('departments')->result_array();
$data['department_list'] = array_combine(array_column($departments, 'id'),array_column($departments, 'dep_name') );
$this->form_validation->set_rules('name', 'Name', 'required|trim');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[user.email]', [
'is_unique' => 'This email has already registered!'
]);
$this->form_validation->set_rules('password1', 'Password', 'required|trim|min_length[3]|matches[password2]', [
'matches' => 'Password dont match!',
'min_length' => 'Password too short!'
]);
$this->form_validation->set_rules('password2', 'Password', 'required|trim|matches[password1]');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar_admin', $data);
$this->load->view('admin/doctors_list', $data);
$this->load->view('templates/footer');
} else {
$email = $this->input->post('email', true);
$role_id = $this->input->post('role_id', true);
$department = $this->input->post('department', true);
$data = [
'name' => htmlspecialchars($this->input->post('name', true)),
'email' => htmlspecialchars($email),
'image' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => htmlspecialchars($role_id),
'department' => htmlspecialchars($department),
'phone' => htmlspecialchars($this->input->post('phone', true)),
'is_active' => 1,
'date_created' => time()
];
$this->db->insert('user', $data);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Congratulation! your account has been created. Please activate your account </div>');
redirect('admin/doctors_list');
}
}
And View
<tr>
<th scope="row"><?= $i; ?></th>
<td><?= $dl['name']; ?></td>
<td><?= $dl['email']; ?></td>
<td><?= $department_list[$dl['department']]; ?> </td>
<td><?= $dl['phone']; ?></td>
<td>
<a type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#editmodal<?= $dl['id']; ?>"><i class="bi bi-pencil-square"></i></a>
<button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#delmodal<?=$dl['id']?>">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
View of the site before fixing
enter image description here
and after fix
enter image description here

Data does not save and not displaying any error - Codeigniter

The data doesn't save without prompting any errors in my code
Here is my code in my Controller
function saveDebit(){
$jevseries=$this->input->post('series');
$account='debit';
$count='1';
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('accountName', 'Account Name', 'required');
$this->form_validation->set_rules('amountDebit', 'Amount', 'required|numeric');
$this->formValidation();
if ($this->form_validation->run() == FALSE) {
$this->entryAccount($jevseries);
} else {
$debitData = array(
'Series' => $jevseries,
'AccountCode' => $this->input->post('accountName'),
'Account' => $account,
'Amount' => $this->input->post('amountDebit'),
'Count' => $count);
$this->Jev_model->entryDebit($debitData);
}
}
Model
function entryDebit($debitData){
$this->db->insert('generalaccount', $debitData);
}
This is my View
<?php echo form_open('Jev/saveDebit'); ?>
<table class="jev_entry" id="jev_entry">
<tr>
<td>Debit</td>
<?php echo form_hidden('series', $series);?>
<td><?php
$account_array = array();
foreach($accountNames as $account ){
$account_array []= $account->accountName;
}
echo form_dropdown('accountName', $account_array,'', 'class="form-control"');
?></td>
</tr>
<tr>
<td>Amount</td>
<td><?php echo form_input('amountDebit','', 'class="form-control"');?><div class="error"><?php echo form_error('amountDebit'); ?></div></td>
</tr>
<tr>
<td></td>
<td align="center"><?php echo '<center>'. form_submit('submit','Save').'</center>'; ?> </td>
</tr>
</table>
I don't know where is the error in this lines.. Your help is very much appreciated.
Okay i have found out what is wrong, The form_input of codeigniter only gives the form with a label. It does not give a name therefore we cannot post it since it doesn't have a name. Do this :)
$data = array(
'name' => 'username',
'id' => 'username',
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%'
);
echo form_input($data);
It's like that and we post the name. Of course you can remove some parameters. More info in the form helper user guide in codeigniter :)
Godluck meyt

Fatal error: Call to undefined method User_m::get() in C:\xampp\htdocs\cms\application\controllers\admin\user.php on line 18

when i open the link 'http://127.0.0.1/cms/index.php/admin/user/edit/1'
this is my user_m model
<?php
class User_m extends CI_Model{
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
public $rules_admin = array(
'name' => array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|valid_email|xss_clean'
),
'order' => array(
'field' => 'order',
'label' => 'Order',
'rules' => 'trim|is_natural'
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback__unique_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|matches[password_confirm]'
),
'password_confirm' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|matches[password]'
)
);
public function __construct()
{
parent::__construct();
}
public function login()
{
$user = $this->db->get_where('users', array(
'email' => $this->input->post('email'),
'password' =>$this->hash($this->input->post('password'))
), TRUE);
if (count($user)) {
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout()
{
$this->session->sess_destroy();
}
public function loggedin()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
this is my user controller
<?php
class User extends Admin_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->data['users'] = $this->db->get_where('users');
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit($id=NULL)
{
$id == NULL || $this->data['user'] = $this->user_m->get($id);
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete($id)
{
}
public function login()
{
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run()==true) {
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}else{
$this->session->set_flashdata('error', 'That email and password combination does not exit');
redirect('admin/user/login', 'refresh');
}
}
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout()
{
$this->user_m->logout();
redirect('admin/user/login');
}
}
this is my edit file.
<div class="modal-header">
<h3><?php echo empty($user->id) ? 'Add a new user' : 'Edit user' . $user->name; ?></h3>
</div>
<div class="modal-body">
<?php echo '<pre>' . print_r($this->session->userdata, TRUE) . '</pre>'; ?>
<?php echo validation_errors(); ?>
<?php echo form_open(); ?>
<table class="table">
<tr>
<td>Email</td>
<td><?php echo form_input('email'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo form_password('password'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Log in', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
this is my index file
<section>
<h2>Users</h2>
<?php echo anchor('admin/user/edit', '<i class="icon-plus"></i> Add a user'); ?>
<table class="table table-striped">
<thead>
<tr>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php if(count($users)): foreach ($users->result() as $user): ?>
<tr>
<td><?php echo anchor('admin/user/edit/' . $user->id, $user->email); ?><td>
<td><?php echo btn_edit('admin/user/edit/'. $user->id); ?><td>
<td><?php echo btn_delete('admin/user/delete/' . $user->id); ?><td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">We could not find any user</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</section>
In your parent construct area on controller try loading model that way all the function in that controller have access to the model else you can load model in the edit function
I can see there is no get function in model also.
public function __construct()
{
parent::__construct();
$this->load->model('user_m'); // Filename should be User_m.php same as class
}
Or
public function edit($id=NULL)
{
$this->load->model('user_m'); // Filename should be User_m.php same as class
$id == NULL || $this->data['user'] = $this->user_m->get($id);
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
Also I see your IP address is loaded in your url. If your using CI3 versions in the config.php you must set this value.
$config['base_url'] = '';
To
$config['base_url'] = 'http://localhost/your_project_name/';

codeigniter update error: Invalid argument supplied for foreach()

I'm a bit confused about this error when I am updating the data. Can anyone help me with this? My codes are the following:
Controller:
public function show_student($id)
{
$data['single_student'] = $this->student_view_model->get_student_id($id);
$this->load->view('view_student_update', $data);
}
public function student_update_info($id, $data)
{
$data = array(
'student_fname' => $this->input->post('first'),
'student_lname' => $this->input->post('last'),
'student_gender' => $this->input->post('gender'),
'student_course' => $this->input->post('course'),
'student_company' => $this->input->post('company')
);
$data['results'] = $this->student_view_model->update_student($this->input->post('hid'), $data);
$this->load->view('view_student_list', $data);
}
Model:
public function get_student_id($id)
{
$query = $this->db->get_where('tbl_student', array('student_id' => $id));
return $query->row_array();
}
public function update_student($id, $data)
{
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
return $this->get_student_id($id);
}
My View ( edit page )
<?php echo form_open('student_update/student_update_info');
$data = array(
'id' => 'input',
'name' => 'hid',
'value' => $single_student['student_id']
);
echo form_hidden($data);
echo form_label('First Name: ', 'first');
$data = array(
'id' => 'input',
'name' => 'first',
'placeholder' => 'Enter First Name',
'value' => $single_student['student_fname']
);
echo form_input($data);
echo form_label('Last Name: ', 'last');
$data = array(
'id' => 'input',
'name' => 'last',
'placeholder' => 'Enter Last Name',
'value' => $single_student['student_lname']
);
echo form_input($data);
echo form_label('Male ', 'gender');
$data = array(
'id' => 'radio',
'name' => 'gender',
'checked' => 'checked',
'value' => $single_student['student_gender']
);
echo form_radio($data);
echo form_label('Female ', 'gender');
$data = array(
'id' => 'radio',
'name' => 'gender',
'value' => $single_student['student_gender']
);
echo form_radio($data);
echo "<br />";
echo form_label('Course', 'course');
$data = array(
'id' => 'input',
'name' => 'course',
'placeholder' => 'Enter Student Course',
'value' => $single_student['student_course']
);
echo form_input($data);
echo form_label('Company', 'company');
$data = array(
'id' => 'input',
'name' => 'company',
'placeholder' => 'Enter Company Name',
'value' => $single_student['student_company']
);
echo form_input($data);
$data = array(
'id' => 'update',
'name' => 'update',
'value' => 'Update'
);
echo form_submit($data);
echo form_close(); ?>
My View ( list of data )
<?php foreach ($results as $row) { ?>
<tr>
<td><?php echo $row->student_fname . " " . $row- >student_lname; ?></td>
<td><?php echo $row->student_course; ?></td>
<td><?php echo $row->student_company; ?></td>
<td>delete
update
</td>
</tr>
<?php } ?>
And this error occurs
error message
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/view_student_list.php
Line Number: 27
Can anyone help me solve this problem?
Please check if any value is present in your variable $results This error comes only when there is no value in the variable with foreach loop.
To avoid these situations always use :
<?php if($results && !empty($results)){ foreach ($results as $row) { ?>
<tr>
<td><?php echo $row->student_fname . " " . $row- >student_lname; ?></td>
<td><?php echo $row->student_course; ?></td>
<td><?php echo $row->student_company; ?></td>
<td>delete
update
</td>
</tr>
<?php } } ?>
Also your result variable will not contain any data to loop since your method update_students does not returns anything.
The main reason you are not getting any results back from your update method is because you are not returning anything.
Secondly, I would change your get_student_id() method as it doesn't quite fit with MVC principals. It works for this particular task, however, you should really be getting the uri value in the controller and then passing it through to your model:
Controller method:
public function show_student($id)
{
$data['single_student'] = $this->student_view_model->get_student_id($id);
$this->load->view('view_student_update', $data);
}
Assuming that "show_student" would be the 2nd uri segment you can do the above.
Model method:
public function get_student_id($id)
{
$query = $this->db->get_where('tbl_student', array('student_id' => $id));
return $query->row_array();
}
This way you can get the row for the student without depending on the student_id always being the 3rd uri segment.
So, with you're results method, you could:
Controller Meothod
public function update_student()
{
$data = array(
'student_fname' => $this->input->post('first'),
'student_lname' => $this->input->post('last'),
'student_gender' => $this->input->post('gender'),
'student_course' => $this->input->post('course'),
'student_company' => $this->input->post('company')
);
$data['results'] = $this->student_view_model->update_student($this->input->post('hid'), $data);
$this->load->view('view_student_list', $data);
}
Model Method:
public function update_student($id, $data)
{
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
return $this->get_student_id($id);
}
Again, with models you should always pass data to them (for quite a few reasons)!
Lastly, I would also think about change the name of get_student_id() to something like get_student_by_id or get_student as get_student_id() suggests t me that you are just going to be getting the id. Also, you really should look at using the Form Validation in codeigniter as your code is very, Very vulnerable at the minute.
Hope this helps!

Update rows in MySQL table with CodeIgniter

So I'm new to PHP and MySQL generally, and MVC applications. Forgive me if this is a question that has been answered already, I couldn't find anything that was crystal clear and showed the complete MVC flow of this.
So I have an HTML table full of inputs populated by data in a, I generate a form for each row as a separate table, and a submit button for each. I want the update button to update only the row associated with the generated form.
If remove this->db->where('id', $id); from the model it updates all rows in the table with the same info, with it present nothing is updated.
Any help or an alternative method for achieving this would be most appreciated. The controller function is also not pretty bad I think.
Thank you.
VIEW
<?php foreach($log->result() as $row): ?>
<?=form_open('hq/update_entry');?>
<table class="editLog">
<tr>
<td><?php
$data = array(
'name' => 'no',
'value' => $row->no
);
echo form_input($data);
?></td>
<td><?php
$data = array(
'name' => 'date',
'value' => $row->date
);
echo form_input($data);
?></td>
<td><?php
$data = array(
'name' => 'artist',
'value' => $row->artist
);
echo form_input($data);
?></td>
<td><?php
$data = array(
'name' => 'title',
'value' => $row->title
);
echo form_input($data);
?></td>
<td><?php
$data = array(
'name' => 'long',
'value' => $row->long
);
echo form_input($data);
?></td>
<td><?php
$data = array(
'name' => 'lat',
'value' => $row->lat
);
echo form_input($data);
?></td>
<td>
<?php
echo form_hidden('id', $row->id);
$data = array(
'class' => 'updateSubmit',
'value' => '✚'
);
echo form_submit($data);
?></td>
</tr>
</table>
<?=form_close();?>
CONTROLLER
function update_entry()
{
$this->load->model('update_entry_model');
if($query = $this->update_entry_model->update())
{
$this->index();
}
else
{
redirect('hq');
}
}
MODEL
<?php
class Update_entry_model extends CI_Model {
function update()
{
$data = array(
'no' => $this->input->post('no'),
'date' => $this->input->post('date'),
'artist' => $this->input->post('artist'),
'title' => $this->input->post('title'),
'long' => $this->input->post('long'),
'lat' => $this->input->post('lat')
);
$this->db->where('id', $id);
$this->db->update('entries', $data);
}
}
Without doing further investigation, I see that in the model function update(), you are missing
$id = $this->input->post('id');
The reason why adding this->db->where('id', $id); doesn't update anything is because $id is not currently set to any value.

Categories