i have 2 tables 'userlogin' and 'user' and then 1 have a form which is 1 form inserting into 2 tables, so far i manage to insert the data but when it has to do with "primary key" and "foreign key" it has problem, as u can see from code below id_login from table userlogin is a primary key and id_login from table user is a foreign key the problem is when i inserting the data, id_login from userlogin has it value while in table user it has no value, below are my code, is there any simple way or am i doing something wrong?
Controller
function add()
{
$this->form_validation->set_rules('nama','Nama Lengkap','required');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
$this->form_validation->set_rules('jenis_user','Jenis User','required');
$this->form_validation->set_rules('alamat','alamat','required');
$this->form_validation->set_rules('hp','hp','required');
$this->form_validation->set_rules('email','email','required');
if($this->form_validation->run()==TRUE)
{
$username=$this->input->post('username',TRUE);
$params = array(
'nama' => $this->input->post('nama',TRUE),
'username' => $this->input->post('nama',TRUE),
'password' => md5($this->input->post('password',TRUE)),
'jenis_user' => $this->input->post('jenis_user',TRUE),
'alamat' => $this->input->post('alamat',TRUE),
'hp' => $this->input->post('hp',TRUE),
'email' => $this->input->post('email',TRUE),
);
if($this->Admin_model->cek_username($username)){
if($this->Admin_model->user_daftar($username,$params))
{
set_header_message('success','Tambah Pengguna','Berhasil menambahkan pengguna');
redirect(base_url(akses().'/pengguna'));
} else {
set_header_message('danger','Tambah Pengguna','Gagal menambahkan pengguna');
redirect(base_url(akses().'/pengguna/add'));
}
} else {
set_header_message('danger','Oops.. Maaf','Username sudah ada yang menggunakan');
redirect(base_url(akses().'/pengguna/add'));
}
} else {
$meta['judul']="Tambah Pengguna";
$this->load->view('tema/header',$meta);
$d['jenis_user']=$this->Admin_model->user_akses_data();
$this->load->view(akses().'/pengguna/penggunaadd',$d);
$this->load->view('tema/footer');
}
}
Model
function user_daftar($username,$params)
{
if($this->db->insert('userlogin', $params)) {
return true;
} else{
return false;
}
}
thank you
Use two different arrays and two different functions in model to insert different data in two different tables.
I think following code will work, if same data for both tables otherwise you need to make two arrays.
function user_daftar($username,$params)
{
if($this->db->insert("userlogin", $params)) {
$id_login=$this->db->insert_id(); // user login id
$params["id_login"]=$id_login;
$this->db->insert("user", $params);
return true;
} else{
return false;
}
}
first separate the data if based on Table attribute then pass two the model
$params = array(
'nama' => $this->input->post('nama',TRUE),
'username' => $this->input->post('nama',TRUE),
'password' => md5($this->input->post('password',TRUE)),
);
$params2 = array(
'jenis_user' => $this->input->post('jenis_user',TRUE),
'alamat' => $this->input->post('alamat',TRUE),
'hp' => $this->input->post('hp',TRUE),
'email' => $this->input->post('email',TRUE),
);
$this->Admin_model->modelXXX($$params1,$params2)
one function on the model side with two param but one thing you have to consider that first, insert a data to the reference table $id_login=$this->db->insert_id(); then insert the second table
function modelXXX($params1,$params2)
{
if($this->db->insert("userlogin", $params1)) {
$id_login=$this->db->insert_id(); // user login id
$params["id_login"]=$id_login;
$this->db->insert("user", $params2);
return true;
} else{
return false;
}
}
Related
I'm currently working on a project that has an accounts management section where the system admin creates the user accounts.
The [Users] table has a column named "Organization_name", which is the user's represented organization. After submitting the form, "Organization_name" will then be also added to the [Organization] table, under the [name] field. The two tables are related by the "user_id" column (taken from the "id" column of the [Users]).
I managed to create a working code to add a [Users] account that also adds the organization_name to the [Organization] table, although now I'm wondering how can I make a function that will also edit the rows in the [Organization] table whenever I edit the fields in [User].
(ex. I changed the "organization_name" field in [Users] with id=1 from "Organization A" to "Organization B," the "name" field in [Organization] with user_id=1 should also change from "Organization A" to "Organization B" too).
NOTE: "role_id" determines what kind of account permissions a user account will have, it doesn't affect the question but I'll leave it in the code snippet below just in case.
I'll attach the codes that I used below:
UserController.php
private static function createUser(Request $request)
{
$user = new User();
$user->email = $request->get('email');
$user->organization_name = $request->get('organization_name');
$user->password = Hash::make($request->get('password'));
$user->role_id = $request->get('role_id');
return $user;
}
private static function createSubUser(Request $request, $user_id)
{
$role_id = $request->get('role_id');
if($role_id == 1)
{
$sub_user = new Organization();
$sub_user->user_id = $user_id;
$sub_user->name = $request->get('organization_name');
}
elseif($role_id == 2)
{
$sub_user = new Staff();
$sub_user->user_id = $user_id;
}
elseif($role_id == 3)
{
$sub_user = new Administrator();
$sub_user->user_id = $user_id;
}
return $sub_user;
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|string|email|max:255|unique:users',
'organization_name' => 'required|string|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = static::createUser($request);
$user->save();
$sub_user = static::createSubUser($request, $user->id);
$sub_user->save();
}
public function updateUserInfo(Request $request)
{
$user = User::find($request->id);
if($user->email == $request->email){
$check_email = false;
}
else{
$check_user = User::where('email', $request->email)->first();
if (!empty($check_user)) {
$check_email = true;
}
else {
$check_email = false;
}
}
if($check_email === true)
{
return response()->json([
'success' => false,
'error' => "User with the registered email of {$request->input('email')} already exists",
]);
}
else
{
$user = User::where('id', $request->id)->update([
'email' => $request->input('email'),
'organization_name' => $request->input('organization_name'),
'role_id' => $request->input('role_id')
]);
return response()->json([
'success' => true,
'user' => $user
]);
}
}
Thank you!
Why you need to add user_id on organization??
An organzation should have many students or users.No need to store organization_name on users table just save the id of organization.When you need to update organization name just update it on organization table.Because you don't need to change in user table you just save here id. Feel free to comment if you have any confussion.
I have table which have multiple reference to ohter tables like
user
id name email
categories
id title
user_categories
user_id category_id
Here a user will have multiple category associated with him/her
I am able to save these successfully with new records like following
View File:
echo $form->field($package_categories, 'category_id')->dropDownList( ArrayHelper::map(
StudyMaterialCategories::find()->all(), 'id', 'title'),
['multiple' => true]
);
Save New record:
$model = new Packages();
$package_categories = new PackageCategories();
$request = Yii::$app->request;
if ($request->isPost) {
$transaction = Yii::$app->db->beginTransaction();
try {
$post = $request->post();
$model->load($post);
$model->save();
foreach ($post['PackageCategories']['category_id'] as $key => $value) {
$package_categories = new PackageCategories();
$package_categories->category_id = $value;
$package_categories->package_id = $model->id;
$package_categories->save();
}
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
} catch (Exception $ex) {
$transaction->rolback();
Yii::$app->session->setFlash("error", $ex->getMessage());
}
}
Till now It's running successfully.
But I'm stuck when going to update the table. The problem part is dropdown list. How to set multiple selected option as per database if I'm coming with array of object.
Have a look on the following code
$package_categories = PackageCategories::find()
->where('package_id=:package_id', ['package_id' => $id])->all();
if (count($package_categories) < 1) {
$package_categories = new PackageCategories();
}
$request = Yii::$app->request;
if ($request->isPost) {
$transaction = Yii::$app->db->beginTransaction();
try {
$post = $request->post();
$model->load($post);
$model->save();
$package_categories = new PackageCategories();
$package_categories->deleteAll(
"package_id=:package_id",
[':package_id' => $model->id]
);
foreach ($post['PackageCategories']['category_id'] as $key => $value) {
$package_categories = new PackageCategories();
$package_categories->category_id = $value;
$package_categories->package_id = $model->id;
$package_categories->save();
}
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
} catch (Exception $ex) {
$transaction->rolback();
Yii::$app->session->setFlash("error", $ex->getMessage());
}
}
if I try to get first object of the array $package_categories of only able to set selected one option
This is an example code of a model class Permit which has a many to many relationship with Activity through PermitActivity (pivot table model).
Model Class Activity
public class Permit extends \yii\db\ActiveRecord {
public $activities_ids;
...
public function rules() {
return [
...
[['activities_ids'], 'safe'],
...
];
}
...
// Method called after record is saved, be it insert or update.
public function afterSave($insert, $changedAttributes) {
// If this is not a new record, unlink all records related through relationship 'activities'
if(!$this->isNewRecord) {
// We unlink all related records from the 'activities' relationship.
$this->unlinkAll('activities', true);
// NOTE: because this is a many to many relationship, we send 'true' as second parameter
// so the records in the pivot table are deleted. However on a one to many relationship
// if we send true, this method will delete the records on the related table. Because of this,
// send false on one to many relationships if you don't want the related records deleted.
}
foreach($this->activities_ids as $activity_id) {
// Find and link every model from the array of ids we got from the user.
$activity = Activity::findOne($activity_id);
$this->link('activities', $activity);
}
parent::afterSave($insert, $changedAttributes);
}
...
// Declare relationship with Activity through the pivot table permitActivity
public function getActivities(){
return $this->hasMany(Activitiy::className(), ['id' => 'activity_id'])
->viaTable('permitActivity',['permit_id' => 'id']);
}
...
public function afterFind(){
parent::afterFind();
$this->activities_id = ArrayHelper::getColumn($this->activities, 'id');
}
}
This way the model class is the one responsible for creating and updating the relationship using the pivot table.
The most important thing is to have the relationship method declared correctly.
Edit
This is an example of the view using kartikv\widgets\Select2. I don't really know if dropDownList supports multiple select, however Select2 has so many useful features i usually use it over other options.
echo $form->field($model, 'activities')->widget(Select2::classname(), [
'data' => $data,
'options' => [
'placeholder' => '...'
],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
],
]);
Code-igniter Session is not storing data, it only saves the Email which we are entering in input box in login-form. I set this $config['sess_use_database'] = TRUE; and created a ci_sessions table also in DB but no sake. I tried this on both versions on code-igniters(2 & 3) Please help me to sort out this problem. Thank you. This is my code. First one is controller and the second one is model.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$query = $this->passenger_login_model->validate();
if($query)
{
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $query->P_ID,
'CNIC' => $query->CNIC
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
and as output, it only shows me the user#user.com not P_ID
and this is model
class Passenger_Login_model extends CI_Model
{
/*`passenger`(`P_ID`, `Name`, `Image`, `CNIC`, `Passport_No`, `Gender`, `Email`,
`Password`, `Phone_No`, `Mob_No`, `Address_1`, `Address_2`, `Date` */
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data)->result();
$c = count($rec);
if($c>0)
{
return true;
}
else
{
return false;
}
}
function is_logged_in()
{
$this->load->library('session');
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.'.anchor('login',"Login");
die();
}
}}
You should return the data fetch from your model query, use fetch function to do that, for more reference click, So your model validate function should be
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data);
return $rec->result_array(); // returns data as array // might help you
}
return $res->result_array(); will return multipdimentional array of data from db, to know more about result_array() check this
Session issue is from your controller function the result is array now.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$result_data = $this->passenger_login_model->validate();
// result data is array now
if(is_array($result_data) && count($result_data) > 0)
{
// var_dump($result_data); // check this var_dump you will get multidimensional array
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $result_data[0]['P_ID'],
'CNIC' => $result_data[0]['CNIC']
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
Hope this help, Happy coding.
My problem solved, i just updated the model to this...
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$query = $this->db->get('passenger');
if ($query->num_rows())
{
return $query->row();
}
}
The model:
function validate()
{
$this->db->where('username',$this->input->post('username'));
$this->db->where('password',md5($this->input->post('password')));
$query = $this->db->get('memberships');
if($query->num_rows() == 1)
{
return TRUE;
}
}
function validate_admin()
{
$this->db->where('adminname',$this->input->post('username'));
$this->db->where('password',md5($this->input->post('password')));
$query = $this->db->get('admin');
if($query->num_rows() == 1)
{
return TRUE;
}
}
The controller
function validate_credentials()
{
$this->load->model('membership_model');
if($this->membership_model->validate())
{
$this->db->where('username',$this->input->post('username'));
$get_profile_info = $this->db->get('memberships');
if($get_profile_info->num_rows() > 0){
foreach ($get_profile_info->result() as $row)
{
$info = array('firstname' => $row->firstname,
'lastname' => $row->lastname,
'email_address' => $row->email_address
);
}
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $info['firstname'],
'lastname' => $info['lastname'],
'email_address' => $info['email_address'],
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('/site/main_menu');
}}
else if($this->membership_model->validate_admin())
{
echo "admin";
}
else
{
redirect('login');
}
}
The if else if statement is not working correctly. The program test the first condition and if it returns false skips the second condition even if that is TRUE and execute the else statement. I'm not sure what is going worng here.
Refactor your one controller method into different methods - one for Members and one for Admin to start. And because you are calling separate database tables would suggest having a separate model for each.
Because you are interacting with a database table getting the profile information should happen in a model (not the controller).
This is a personal preference but i would set the session data in a model as well. Also there might be issues with your foreach and then getting the value $info['first name'].
Validate the form data first before sending to your database. Its safer and its better for your users - if they forget to put in the password you want to show them the form again with a helpful message. http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
and remember when in doubt -- echo it out.
I want to add form validation if the ip_address duplicated just
stay on current page or show me any kind of message.
this is the model code
public function add_vote($option_id)
{
$this->db->insert($this->votes_table, array(
'option_id' => $option_id,
'ip_address' => $this->input->ip_address(),
'timestamp' => time()
));
return ($this->db->affected_rows() == 1) ? TRUE : FALSE;
}
this is the controler
public function vote($poll_id, $option_id)
{
if ( ! $this->poll_lib->vote($poll_id, $option_id))
{
$data['base_styles'] = 'public_html/res/css/base.css';
$data['title'] = 'Sorry an error occured';
$data['error_message'] = $this->poll_lib->get_errors();
$this->load->view('header');
$this->load->view('www/posts/postclose', $data);
}
else
{
redirect('posts', 'refresh');
}
}
hear if i add new vote it's shows me database error as the column is duplicate so i don't want to show that, if it redirect me to any other page will be great if stay on current page still ok or any pop up message.
Do a check before inserting into database.
public function add_vote($option_id)
{
$query = $this->db->get_where($this->votes_table, array('ip_address' => $this->input->ip_address()));
if($query->num_rows() < 1)
{ $this->db->insert($this->votes_table, array(
'option_id' => $option_id,
'ip_address' => $this->input->ip_address(),
'timestamp' => time()
));
return "Successfully Inserted";
}else{
return "Duplicate";
}
}
In your controller handle the response and display accordingly