Home > Net >  Get value from a select and insert id insetad of string into database - PHP MVC
Get value from a select and insert id insetad of string into database - PHP MVC

Time:12-13

Hello I'm having a problem I can't solve, im finishing a registration form, user provides username, email password and has to select a value from a select field, once users register instead of sending the option value as string it should send the id but I cant figure out how to do it.

This is the register action on the RegisterController (on the dd the value gets passed as string)

public function reg(){

    $email=$this->request->post('email');
    $username=$this->request->post('username');
    $password=$this->request->post('password');
    $password2=$this->request->post('password2');
    $role = $this->request->post('role');

    if(isset($email) && !empty($email) 
        && isset($username) && !empty($username)
        && isset($password) && !empty($password) 
        && isset($password2) && !empty($password2)
        && isset($role) && !empty($role)){
        if($password == $password2){
            $pass=password_hash($password,PASSWORD_BCRYPT,['cost'=>4]);
            try {
                $data=[$username,$email,$pass,$role];
                dd($data);
                Registry::get('database')->insert($data);
                Controller::redirectTo('login');
            } catch (\PDOException $e) {
                return false;
            }
        } else {
            Controller::redirectTo('index');
        }
    }
}

Here's the register view (tried to get the id of each role in the value field but it stops showing the option on the view when I do that )

<label  for="role">Role:</label>
            <select  name="role" id="role">
            <?php foreach($roles as $role):?>
                <option value="<?php echo $role->id;?>" ><?php echo $role->role;?></option>
            <?php endforeach; ?>
            </select><br>

If anyone needs another file like the QueryBuilder (to see the insert) or any other file I'll provide it if needed.

CodePudding user response:

you can try to typecast the value to integer like below:

$role = intval($this->request->post('role'));

php docs: https://www.php.net/manual/en/function.intval.php

  • Related