benedmunds / CodeIgniter-Ion-Auth

Simple and Lightweight Auth System for CodeIgniter
http://benedmunds.com/ion_auth/
MIT License
2.35k stars 1.14k forks source link

Error Number: 1452 Cannot add or update a child row: a foreign key constraint fails #615

Closed satyajit98300 closed 9 years ago

satyajit98300 commented 9 years ago

Its showing error. Error Number: 1452

Cannot add or update a child row: a foreign key constraint fails (trydoc.users_groups, CONSTRAINT fk_users_groups_groups1 FOREIGN KEY (group_id) REFERENCES groups (id) ON DELETE CASCADE ON UPDATE NO ACTION)

INSERT INTO users_groups (group_id, user_id) VALUES (0, 7)

Filename: C:\EasyPHP-DevServe\data\localweb\trydocpro\system\database\DB_driver.php

Line Number: 330

need help.

benedmunds commented 9 years ago

why are you inserting with a group id 0? Do you have a group setup with id 0?

satyajit98300 commented 9 years ago

Here is the code, what i m using for user register.


if ($this->form_validation->run() == true) { $username = str_replace(' ' , '-', strtolower($this->input->post('full_name'))); $email = strtolower($this->input->post('email')); $password = $this->input->post('password'); $pin = unique_number(); $additional_data = array( 'full_name' => $this->input->post('full_name'), 'city' => $this->input->post('city'), 'state' => $this->input->post('state'), 'phone' => $this->input->post('phone'), 'pin' => $pin ); $group = array('3');

    }
    if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data, $group))
    {
        //check to see if we are creating the user
        //redirect them back to the admin page
        $this->session->set_flashdata('now_register_email', $email);
        redirect("register", 'refresh');
    }

Here is the config

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /**

/* ------------------------------------------------------------------------- Tables.
Database table names.

*/ $config['tables']['users'] = 'users'; $config['tables']['groups'] = 'groups'; $config['tables']['users_groups'] = 'users_groups'; $config['tables']['login_attempts'] = 'login_attempts';

/* Users table column and Group table column you want to join WITH.
Joins from users.id
Joins from groups.id

*/ $config['join']['users'] = 'user_id'; $config['join']['groups'] = 'group_id';

/* ------------------------------------------------------------------------- Hash Method (sha1 or bcrypt)
Bcrypt is available in PHP 5.3+
IMPORTANT: Based on the recommendation by many professionals, it is highly recommended to use
bcrypt instead of sha1.
NOTE: If you use bcrypt you will need to increase your password column character limit to (80)
Below there is "default_rounds" setting. This defines how strong the encryption will be,
but remember the more rounds you set the longer it will take to hash (CPU usage) So adjust
this based on your server hardware.
If you are using Bcrypt the Admin password field also needs to be changed in order login as admin:
$2a$07$SeBknntpZror9uyftVopmu61qg0ms8Qv1yV6FG.kQOSM.9QhmTo36
Be careful how high you set max_rounds, I would do your own testing on how long it takes
to encrypt with x rounds.
salt_prefix: Used for bcrypt. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix
Versions 5.3.7 or greater should use the default of "$2y$".

*/ $config['hash_method'] = 'bcrypt'; // sha1 or bcrypt, bcrypt is STRONGLY recommended $config['default_rounds'] = 8; // This does not apply if random_rounds is set to true $config['random_rounds'] = FALSE; $config['min_rounds'] = 5; $config['max_rounds'] = 9; $config['salt_prefix'] = '$2y$';

/* ------------------------------------------------------------------------- Authentication options.
maximum_login_attempts: This maximum is not enforced by the library, but is
used by $this->ion_auth->is_max_login_attempts_exceeded().
The controller should check this function and act
appropriately. If this variable set to 0, there is no maximum.

*/ $config['site_title'] = "Example.com"; // Site Title, example.com $config['admin_email'] = "admin@example.com"; // Admin Email, admin@example.com $config['default_group'] = 'members'; // Default group, use name $config['admin_group'] = 'admin'; // Default administrators group, use name $config['identity'] = 'email'; // A database column which is used to login with $config['min_password_length'] = 8; // Minimum Required Length of Password $config['max_password_length'] = 20; // Maximum Allowed Length of Password $config['email_activation'] = FALSE; // Email Activation for registration $config['manual_activation'] = FALSE; // Manual Activation for registration $config['remember_users'] = TRUE; // Allow users to be remembered and enable auto-login $config['user_expire'] = 86500; // How long to remember the user (seconds). Set to zero for no expiration $config['user_extend_on_login'] = FALSE; // Extend the users cookies every time they auto-login $config['track_login_attempts'] = FALSE; // Track the number of failed login attempts for each user or ip. $config['track_login_ip_address'] = TRUE; // Track login attempts by IP Address, if FALSE will track based on identity. (Default: TRUE) $config['maximum_login_attempts'] = 3; // The maximum number of failed login attempts. $config['lockout_time'] = 600; // The number of seconds to lockout an account due to exceeded attempts $config['forgot_password_expiration'] = 0; // The number of milliseconds after which a forgot password request will expire. If set to 0, forgot password requests will not expire.

/* ------------------------------------------------------------------------- Cookie options.
remember_cookie_name Default: remember_code
identity_cookie_name Default: identity

*/ $config['remember_cookie_name'] = 'remember_code'; $config['identity_cookie_name'] = 'identity';

/* ------------------------------------------------------------------------- Email options.
email_config:
'file' = Use the default CI config or use from a config file
array = Manually set your email config settings

*/ $config['use_ci_email'] = FALSE; // Send Email using the builtin CI email class, if false it will return the code and the identity $config['email_config'] = array( 'mailtype' => 'html', );

/* ------------------------------------------------------------------------- Email templates.
Folder where email templates are stored.
Default: auth/

*/ $config['email_templates'] = 'auth/email/';

/* ------------------------------------------------------------------------- Activate Account Email Template
Default: activate.tpl.php

*/ $config['email_activate'] = 'activate.tpl.php';

/* ------------------------------------------------------------------------- Forgot Password Email Template
Default: forgot_password.tpl.php

*/ $config['email_forgot_password'] = 'forgot_password.tpl.php';

/* ------------------------------------------------------------------------- Forgot Password Complete Email Template
Default: new_password.tpl.php

*/ $config['email_forgot_password_complete'] = 'new_password.tpl.php';

/* ------------------------------------------------------------------------- Salt options
salt_length Default: 22
store_salt: Should the salt be stored in the database?
This will change your password encryption algorithm,
default password, 'password', changes to
fbaa5e216d163a02ae630ab1a43372635dd374c0 with default salt.

*/ $config['salt_length'] = 22; $config['store_salt'] = FALSE;

/* ------------------------------------------------------------------------- Message Delimiters.

*/ $config['delimiters_source'] = 'config'; // "config" = use the settings defined here, "form_validation" = use the settings defined in CI's form validation library $config['message_start_delimiter'] = ''; // Message start delimiter $config['message_end_delimiter'] = ''; // Message end delimiter $config['error_start_delimiter'] = ''; // Error mesage start delimiter $config['error_end_delimiter'] = ''; // Error mesage end delimiter

/* End of file ionauth.php / /_ Location: ./application/config/ion_auth.php */

benedmunds commented 9 years ago

I'm not sure whats happening exactly. It could be that youre passing in the group ID as a string when it should be an integer. Try changing that to an INT and see what happens.

satyajit98300 commented 9 years ago

its same issue. its taking zero,dont know why.

satyajit98300 commented 9 years ago

line no 935 is creating problem. its . its now fixed. removed 2nd condtion.

benedmunds commented 9 years ago

What exactly did you change? Which file?

satyajit98300 commented 9 years ago

its the modal file. there was 2 condition 1)for checking group array checking , if it empty or not 2) for checking if provided, its default group or not.

i just removed 2 condition.

benedmunds commented 9 years ago

hmm ok

jitupatel76877 commented 8 years ago

A Database Error Occurred

Error Number: 1452

Cannot add or update a child row: a foreign key constraint fails (fbuddyco_jobsite.users_groups, CONSTRAINT fk_users_groups_groups1 FOREIGN KEY (group_id) REFERENCES groups (id) ON DELETE CASCADE ON UPDATE NO ACTION)

INSERT INTO users_groups (group_id, user_id) VALUES (0, 82)

Filename: /home/fbuddyco/public_html/job/models/ion_auth_model.php

Line Number: 1393

jitupatel76877 commented 8 years ago

please tell me

jitupatel76877 commented 8 years ago

This my code

$additional_data = array( 'first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'address1' => $this->input->post('address'), 'phone' => $this->input->post('phone'), 'gender' => $this->input->post('gender') );

        if (!$this->ion_auth->email_check($email)){
            $group = array('3');
            $this->ion_auth->register($username, $password, $email, $additional_data, $group);
            //give error when inserting data complete
            redirect('candidate/registration_complete');
        }else{
            $data['error'] = "Email already exists";
            $this->load->view("candidate_registration",$data);
        }
benedmunds commented 8 years ago

Does that group exist? Try using the group name.

jitupatel76877 commented 8 years ago

yes group exist. allready try group name

benedmunds commented 8 years ago

Try changing the 3 in the array to be an integer instead of a string. It shouldn't matter since PHP should type cast it but it's worth a try

Lerp commented 8 years ago

I am having same error. I tried changing to INT but no go.

It is inserting into the users table no problemo, but when it goes to the users_groups table it fails with a 0 for the groupid.

Would there be an issue if I just change the array argument to be just a string?

Was there ever any fix for this?

I am sending in an array like ('3') and it comes up as '0' in the error.

$group = array('3'); // Bussiness admin role $activate_key = random_string('alnum', 32); //random passwod for now $user_id = $this->ion_auth->register($username, $password, $email, $additional_data, $group);

I have three groups in my groups table, 1,2 & 3.

Am I missing a record or something I wonder?

cheers :)

avenirer commented 8 years ago

is it "groupid" or "group_id" inside your table?

Lerp commented 8 years ago

hi there, it is group_id in the users_groups table

Going to double check the config and send another update here soon

cheers, Lerp

Lerp commented 8 years ago

I have adjusted the config as indicated and it is now inserting properly into the users_groups table

cheers & thanks, Lerp :)

azhardev631 commented 1 year ago

Cannot add or update a child row: a foreign key constraint fails in codeigniter 4

<?php

namespace App\Database\Seeds; use App\Models\UserModel; use App\Models\BlogModel; use App\Models\CommentModel; use CodeIgniter\Database\Seeder;

class CommonSeeder extends Seeder { public function run() { $user = new UserModel; $blog = new BlogModel; $comment = new CommentModel;

    $users= [1,2,3,4,5,6];
    $faker = \Faker\Factory::create();
    for($i=0; $i<10;$i++){ 
    $user->save([
        "name"=> $faker->name,
        "email"=>$faker->email,
        "password"=>$faker->password
    ]);
    $blog->save([
        "message"=>$faker->text,
        "created_by"=>$faker->randomElement($array = array ($users))
    ]);
    $comment->save([
        "comment"=>$faker->text,
        "user_id"=>$faker->randomNumber,
        "blog_id"=>$faker->randomNumber
    ]);

    }
}

}

benedmunds commented 1 year ago

Which FK constraint is failing? The group id? Does that group exist?