Add user on Codeigniter 3 - php

Hi i am new here and i dont know how to use codeigniter and now im confused. So i am currently trying to add user data to the database using codeigniter 3.1.10 . When i click the " save " button there's nothing to display. The page was refresh
Can you help me please?
Models:
function add_user($data) {
$this->db->set("username",$data["username"]);
$this->db->set("password",$data["password"]);
$this->db->set("indirizzo",$data["indirizzo"]);
$this->db->set("citta",$data["citta"]);
$this->db->set("cap",$data["cap"]);
$this->db->insert("user");
$ins_id =$this->db->insert_id();
return $ins_id;
}
Controllers:
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('save', '', 'trim|required|number');
if ($this->form_validation->run()) :
$data = array(
"username"=>$this->input->post("username"),
"password"=>$this->input->post("password"),
"indirizzo"=>$this->input->post("indirizzo"),
"citta"=>$this->input->post("citta"),
"cap"=>$this->input->post("cap"),
);
$user_id= $this->user_model->add_user($data);
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
else :
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
endif;
}

Your doing a lot wrong, starting from the fact that your doing stuff from the model in your controller, and you should divide it, otherwise your not using the concept of MVC.
Try something like this, being hard to help you, without seeing the whole code:
Model
function add_user()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'indirizzo' => $this->input->post('indirizzo'),
'citta' => $this->input->post('citta'),
'cap' => $this->input->post('cap')
);
return $this->db->insert('user', $data);
}
Controller
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('indirizzo', 'Indirizzo', 'required');
$this->form_validation->set_rules('citta', 'Citta', 'required');
$this->form_validation->set_rules('cap', 'Cap', 'required');
$errore = true;
if ($this->form_validation->run() === FALSE){ // if doesnt work load your view
$this->load->view('your view');
}
else {
$this->user_model->add_user();
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
}
}
You really should try and search more about it, and learn!
I could learn a lot of the basics of CodeIgniter, watching this channel that has great content, and explains every detail: https://www.youtube.com/playlist?list=PLillGF-RfqbaP_71rOyChhjeK1swokUIS

function add_user($data) {
$this->db->insert("user",$data);
$ins_id =$this->db->insert_id();
return $ins_id;
}
use this in model..
and in controller set rules for each like this
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
// for all other

Related

Use form_validation correctly in CodeIgniter

I have a registration system with CodeIgniter but currently I have no control on email and password. A user can register without putting email or a password.
I have an index() and a register_user function() in my Signup controller but the redirection is not working on success
At the moment I have the following code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Signup extends CI_Controller {
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->load->view('home-view');
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
function register_user(){
$this->load->library('custom_u_id');
$data = array('user_id' => $this->custom_u_id->construct_id('USR'),
'name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $_POST['password'],
);
$this->load->model('signup_model');
$user_details = $this->signup_model->register_user($data);
if (!empty($user_details)){
$user_data = array
(
'user_id' => $user_details['user_id'],
'email' => $user_details['email'],
'name' => $user_details['name'],
'user_type' => $user_details['user_type'],
);
$this->session->set_userdata('sessiondata',$user_data);
if (intval($user_details['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
} else{
redirect('login');
}
}// end of function login
}
Do I need to put the form_validation in my register_user function ? I've tried but the check doesn't work anymore...
I also have in my view the <?php validation_errors();?> function and the <?php form_open(base_url().'signup');?>
looking by your code, i think you want to put register_user() inside validation TRUE since the query is in that method.
so try to change your code to this :
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->register_user();
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
and be sure your form action to like this :
<form action="<?=site_url('/signup/index');?>">

How to send post values in RESTful API using CodeIgniter?

I don't have any idea how to get values please help me to sort this problem. Tell me with a reference if someone already has the code then please share. I'm also curious as how to load spark with cURL with a RESTful API with full procedure
<?php class LoginController extends CI_Controller {
public function index()
{
$this->load->view('admin/header');
$this->load->view('admin/index');
$this->load->view('admin/footer');
}
public function loginCon(){
$this->load->Library('rest');
$this->form_validation->set_rules('email', 'E-mail', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>", "</p>");
if ($this->form_validation->run()==false)
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->session->set_flashdata('login_failed', 'Invalid User Name Password');
}else{
$config = array('server' => "http://api.amid.tech/hsApiV2/api/demo.php/",
'http_user' => 'admin',
'http_pass' => 'xxxxx',
'http_auth' => 'basic',
);
$this->rest->initialize($config);
$method = 'post';
$param = array(
'UserEmail' => $this->input->post('email'), // works fine here
'UserPass' => $this->input->post('password'),
'UserRoleId'=>1
);
$uri = 'adminlogin';
$this->rest->format('application/json');
$result = $this->rest->{$method}($uri, $param);
echo $result;
$this->load->view('admin/admin_header');
$this->load->view('admin/sidebar');
$this->load->view("admin/dashboard");
$this->load->view('admin/dashboard.php');
}
}
public function registerd()
{
$this->load->view('admin/header');
$this->load->view('admin/registration');
$this->load->view('admin/footer');
}
} ?>
To get raw inputs try
// get the raw POST data
$rawData = file_get_contents("php://input");
For validation try
$this->form_validation->set_rules($rawData['email'], 'E-mail', 'required|trim');

Codeigniter doesn't let me update entry, because some fields must be unique

So what I'm trying to do:
Pull User data from database, including email address, username etc.
Edit it
Save it
But I want to keep username and email unique.
And for this I'm setting validation rules like this:
$this->form_validation->set_rules('firstname', 'First Name', 'required|min_length[2]|max_length[15]');
$this->form_validation->set_rules('lastname', 'Last Name', 'required|min_length[2]|max_length[15]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]|is_unique[users.username]');
$this->form_validation->set_rules('password1', 'Password', 'required|matches[password2]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'required');
$this->form_validation->set_rules('group', 'User Group', 'required');
And as you can see I have is_unique[users.username] and is_unique[users.email] rules. But it doesn't let me update my entry using this rules.
So the question is, how can I update database entry, and keep those 2 fields unique(username and email)?
use the call back validation function
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_check_user_email');
function check_user_email($email) {
if($this->input->post('id'))
$id = $this->input->post('id');
else
$id = '';
$result = $this->user_model->check_unique_user_email($id, $email);
if($result == 0)
$response = true;
else {
$this->form_validation->set_message('check_user_email', 'Email must be unique');
$response = false;
}
return $response;
}
in model
function check_unique_user_email($id = '', $email) {
$this->db->where('email', $email);
if($id) {
$this->db->where_not_in('id', $id);
}
return $this->db->get('user')->num_rows();
}
use same for the user name....
In Codeigniter 4
// is_unique[table.field,ignore_field,ignore_value]
$validation->setRules([
'name' => "is_unique[supplier.name,uuid, $uuid]", // is not ok
'name' => "is_unique[supplier.name,uuid,$uuid ]", // is not ok
'name' => "is_unique[supplier.name,uuid,$uuid]", // is ok
'name' => "is_unique[supplier.name,uuid,{uuid}]", // is ok - see "Validation Placeholders"
]);
Eg.
$validation->setRules(['email' => 'required|valid_email|is_unique[users.email,id,4]']);
// 'id' = ignore table field name (users table 'id' field)
// '4' = ignore field value(currnet user id)
codeigniter 4 validation
For Codeigniter 3
Add following helper class (edit_unique_helper.php)
function edit_unique($value, $params) {
$CI =& get_instance();
$CI->load->database();
$CI->form_validation->set_message('edit_unique', "Sorry, that %s is already being used.");
list($table, $field, $current_id) = explode(".", $params);
$query = $CI->db->select()->from($table)->where($field, $value)->limit(1)->get();
if ($query->row() && $query->row()->id != $current_id)
{
return FALSE;
} else {
return TRUE;
}
}
Add to autoload ()
Use edit_unique where you pass an extra parameter which is the id of the row you're editing
eg. $this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|edit_unique[users.user_name.'.$id.']');
Source

Duplicate error in creating a login user

I have used codeigniter code in the below when I create a user if it is already exist it should display a message duplicate value but it displays 1062 error. Pls help to solve the issue.
Controller
function create_member()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->load->view('signup_form');
}
else
{
$this->load->model('membership_model');
if($query = $this->membership_model->create_member())
{
$data['main_content'] = 'signup_successful';
$this->load->view('includes/template', $data);
}
else
{
$this->load->view('signup_form');
}
}
}
Model
function create_member()
{
$new_member_insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email_address' => $this->input->post('email_address'),
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password'))
);
$insert = $this->db->insert('membership', $new_member_insert_data);
if ($this->db->_error_number() == 1062)
{
$this->session->set_flashdata('duplicate_email', 'Duplicate value');
redirect('login');
}
return $insert;
}
It seems that your error is because your database is not allowing to add multiple entries with same username/email, for this you need to add codeigniter is_unique validation on that particular field. Below is example for codeigniter unique validation : $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[membership.username]');
Try to use $this->db->query instead of insert and create a SQL statement using INSERT IGNORE and you can handle the duplicates silently.
Why just not do a previous query to check if the email exists aleady ?
Anyway, you can do something like that:
$query_string = $this->db->insert_string('users', $data);
$this->db->query($query_string.' ON DUPLICATE KEY UPDATE id=id');
// or
$this->db->query(str_replace("INSERT INTO", "INSERT IGNORE INTO", $query_string));
if( $this->db->affected_rows() == 0 ) {
//duplicate email
}

Codeigniter Signup Controller code review

I just started using a MVC framework, especially Codeigniter and i am having some trouble maintaining my code and where to place my functions(controller or model).
For now i am building a sign up system and i have a controller with the name signup.php
This is my code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Signup extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$this->load->view("register/index");
}else{
$this->submitRegistration();
}
}
public function ajaxup(){
if ($this->input->isAjaxRequest()){
header('Content-type: application/json');
$error = false;
$message = '';
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$message = validation_errors();
$error = true;
}else{
$this->_submitRegistration();
$message = 'Successfully registered.';
}
$return = array(
'error' => $error,
'message' => $message
);
$return = json_encode($return);
echo $return;
}
}
public function _submitRegistration(){
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'email' => $email,
'password' => $password
);
$this->load->model('users_model');
$this->users_model->register_user($data);
}
public function check_valid_username($username){
$this->load->model('users_model');
if (!$this->users_model->is_valid_username($username)){
$this->form_validation->set_message('check_valid_username', 'The %s field should contain only letters, numbers or periods');
return false;
}
return true;
}
}
Is there anything i could write better to maintain my code and be readable?
*NOTE:*the function ajaxup is used when a user clicks the button and does an ajax call.
Thanks
Looks pretty good to me. Here are few ideas/suggestions for future improvements:
In index() you are calling $this->submitRegistration() but I think you want to be calling $this->_submitRegistration().
Since you are using the same validation rules in both the index() and ajaxup() methods you could pull pull them out into an array and either make them a property of your controller or put them into a config file.
For documentation see here and here.
$validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
Then in your methods you would do something similar to $this->form_validation->set_rules($validation_rules).
Think about reordering your validation rules. For example, let's take a look at the rules for the username field. If check_valid_username() is making a call to the database (through the user model) then it would probably be better to validate the length requirements before. There's no use making an expensive call to the database if we can determine if the username is invalid.
Make your callback methods private. Right now check_valid_username() is a public method and could potentially be accessed through the URL. Prefix it with an underscore (_check_valid_username()) and then in your validation rules use callback__check_valid_username. Note the two underscores.
If you find yourself needing to use check_valid_username() in multiple controllers you could extend the native form validation library and put it there.
This looks fine to me. You seem to have all the relevant functions located in the user model and you are using the controller to access them. All I can suggest is read up on MVC theory if you feel unsure.
This is a good article:
http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html

Categories