简体   繁体   English

不使用yii将值插入数据库的一列中

[英]Not inserting the value in one column in db using yii

I am new to YII . 我是YII新手。 Problem is that I am having issue s in entering the user record. 问题是我在输入用户记录时遇到问题。 It is not inserting the complete record in db. 它没有在db中插入完整的记录。 skipping last field. 跳过最后一个字段。 Below are my controller and model. 以下是我的控制器和型号。 It is not inserting the $heard_about_us in database. 它没有在数据库中插入$heard_about_us

class UsersController extends Karmora
user controller action 
    public function actionSignUp($affusername=null)
    {
        //echo "all is well";exit;
        if(!empty($affusername)){
            $this->VarifyUser($affusername);
            $user_data = Users::model()->getUsersByUserName($affusername);  //getting user information
        }
        else {
            $user_data = '';
        }
        //echo '<pre>'; print_r($user_data); exit;


        $this->ticker_news =  NewsTicker::model()->getTickerNews();

        $model=new Users('signup'); //apply rules if user comes directly to signup page

        //echo '<pre>'; print_r($model); exit;

        // uncomment the following code to enable ajax-based validation
        if(isset($_POST['ajax']) && $_POST['ajax']==='users-signup-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        $referrer_data="";
        if(empty($affusername))
        $referrer_data = $model->getUsersByRole("SuperAdmin");
        else{
            $referrer_data = $model->getUsersByUserName($affusername);

            //if invalid affiliate name then redirect to home page
            if(!$referrer_data) {
                $this->redirect($this->base_url.'/home');
            }
        }

        if(isset($_POST['Users']))
        {   
            $_POST['Users']['optin'] = 0;
            $_POST['Users']['registration_date'] = date('y-m-d h:i:s');
            $_POST['Users']['role'] = "Affiliate";
            $_SESSION['newUser']    =   $_POST['Users'];

            $model->attributes=$_POST['Users'];
            if($model->validate())
            {
                //assigning referral key to new created user
                $model->referrer = $referrer_data['id'];
                $model->state = $_POST['Users']['state'];
                // $model->subid = uniqid();

                /*
                 $this->displayData($_POST);
                 exit;
                 */

                /*
                 Yii::import('application.vendors.*');
                 require_once('iPayout.php');
                 $config = array(
                 'MerchantGUID' => 'abcdefghi;dks;dfk',
                 'MerchantPassword' => 'password',
                 'eWalletAPIURL' => "https://www.testewallet.com/eWalletWS/ws_adapter.aspx"
                 );

                 $iPayout_obj = new iPayout($config);
                 $response = $iPayout_obj->iPayout_GetUniqueUserName(array('UserName'=>$_POST['Users']['username']));

                 //echo $response;

                 $check_username = json_decode($response);
                 $model->ewallet_username = $check_username->valid_user_name;
                 */

                // Jan 17, 2014, By IK, added new API
                // Import Authorize.Net SDK from vendors
                Yii::import('application.vendors/anet_php_sdk.*');
                require_once('AuthorizeNet.php');

                // If coupon code then
                $trial = false;
                if ($_POST['Users']['token']) {
                    $trial = true;
                }

                /* Authorize.Net test credit card numbers
                 - American Express Test Card: 370000000000002
                 - Discover Test Card: 6011000000000012
                 - Visa Test Card: 4007000000027
                 - Second Visa Test Card: 4012888818888
                 - JCB: 3088000000000017
                 - Diners Club/ Carte Blanche: 38000000000006*/

                // Set the subscription fields.
                $amount = 25;
                $subscription = new AuthorizeNet_Subscription();
                $subscription->name = $_POST['Users']['username']; //Merchant-assigned name for the subscription
                $subscription->intervalLength = "1";
                //$subscription->refId = "willid";
                $subscription->intervalUnit = "months";
                $subscription->startDate = date('Y-m-d'); //(YYYY-MM-DD) "2014-02-12";
                $subscription->totalOccurrences = "9999";
                $subscription->amount = $amount;

                if ($trial) {
                    $subscription->trialOccurrences = "3";
                    $subscription->trialAmount = "0";
                }

                $subscription->creditCardCardNumber = $_POST['Users']["cardNumber"];
                $subscription->creditCardExpirationDate = $_POST['Users']["exp_year"].'-'.$_POST['Users']["exp_month"]; //"2015-10";
                $subscription->creditCardCardCode = $_POST['Users']["cardCode"];
                $subscription->billToFirstName = $_POST['Users']["first_name"];
                $subscription->billToLastName = $_POST['Users']["last_name"];

                // Create the subscription.
                $request = new AuthorizeNetARB(API_LOGIN_NAME, API_TRANSACTION_KEY);
                $response = $request->createSubscription($subscription);
                $isOk = $response->isOk();

                // Payment is successfull and create user account
                if ($isOk) {

                    // Authorize.Net Subscription id
                    $subscription_id = $response->getSubscriptionId();

                    if ($model->save()){

                        /******* Create blog ************/
                        $user_id = yii::app()->db->lastInsertID;
                        Yii::app()->session['username'] =   $_POST['Users']['username'];
                        yii::app()->session['user_id'] = $user_id;
                        yii::app()->session['first_name'] = $_POST['Users']['first_name'];
                        yii::app()->session['email'] = $_POST['Users']['email'];
                        Yii::app()->session['password'] =   $_POST['Users']['password'];
                        $db_user_data = $model->findByPk($user_id);
                        if(!(Users::model()->updateAll(array("status" => "active", "subid" => $subscription_id), "id = $user_id"))) {
                            //echo 'user not updated';
                        }

                        // Jan 17, 2014, Commented by IK, old Authorize.net is replaced by Authorize.Net SDK
                        /*
                         Yii::import('application.vendors.*');
                         require_once('karmora_authorizenet.php');

                         $config = array(
                         'loginname' => '8QqN8Q9p4P',
                         'transactionkey' => '7653C9N3VumpMn26',
                         'host' => "apitest.authorize.net",
                         'path' => "/xml/v1/request.api"
                         );

                         $kauthnet_obj = new karmora_authorizenet($config);
                         $authnet_data['amount'] = '25.0';
                         $authnet_data['refId'] = $db_user_data["subid"];
                         $authnet_data['name'] = $db_user_data["username"]; //Merchant-assigned name for the subscription
                         $authnet_data['length'] = 1;
                         $authnet_data['unit'] = 'months';
                         $authnet_data['startDate'] = date('Y-m-d'); //2013-11-05 (YYYY-MM-DD)
                         $authnet_data['totalOccurrences'] = '9999';
                         //$authnet_data['trialOccurrences'] = 2;
                         //$authnet_data['trialAmount'] = 0;
                         $authnet_data['cardNumber'] = $_POST['Users']["cardNumber"];
                         $authnet_data['expirationDate'] = $_POST['Users']["exp_year"].'-'.$_POST['Users']["exp_month"];
                         $authnet_data['firstName'] = $db_user_data["first_name"];
                         $authnet_data['lastName'] = $db_user_data["last_name"];
                         $con = $kauthnet_obj->setARBContent($authnet_data);
                         //print_r($con);
                         //print_r($kauthnet_obj);
                         $subscription_create = $kauthnet_obj->createARBSubscription();
                         */

                        /*
                            Array
                            (
                            [refId] => 529722f838d54
                            [resultCode] => Ok
                            [code] => I00001
                            [text] => Successful.
                            [subscriptionId] => 1895540
                            )
                         */

                        /******* Authorize.net END **********/

                        /*  Commented by IK, we don't need blog at the moment
                         *  Jan 10, 2014
                         *  Blog creation login is not working at the moment due to some bug
                         */

                        // Create blog
                        //$is_created = $this->CreateBlog($db_user_data);
                        /*if($is_created){
                            //echo 'BLOG CREATED';exit;
                            $this->updatedBlogUserStatus();
                            $this->redirect($this->base_url.'/videos');
                            }
                            else{

                            $subject = "Blog not created for user";
                            $message = "Error while creating a blog for following user<br><br>";
                            $message.="<b>User Detail:</b><br>";
                            $message.="Username: ".$db_user_data['username']."<br>";
                            $message.="Email: ".$db_user_data['email']."<br>";
                            $this->SendKarmoraMail($subject, $message, 'irfan.k@dprodigy.com');
                            //mail($to,$subject,$message,$headers)
                            }*/
                        /********** end create blog *****************/

                        $Loginmodel=new LoginForm();
                        $LoginFormData['username'] = $_POST['Users']['username'];
                        $LoginFormData['password'] = $_POST['Users']['password'];

                        //print_r($LoginFormData);

                        $Loginmodel->attributes=$LoginFormData;

                        if(!($Loginmodel->validate() && $Loginmodel->login())){
                            //echo 'Login failed';
                            $this->redirect($this->base_url); // Uncomment later
                        }
                        else if($Loginmodel->validate() && $Loginmodel->login()) {

                            $this->redirect($this->base_url.'/congrats'); // Uncomment later
                            //self::actionSignupCongrats();
                        }
                    }
                    else {
                        $this->setFlashError("Unable to register user, please try again");
                        return false;
                    }
                }
                else {
                    $error_text = $response->getResponseText();
                    $error_code = $response->getResponseCode();
                    if ($error_code == 'E00003') {
                        $error_text = 'Credit card number is invalid';
                    }
                    // Add custom error messages
                    $model->addError('cardNumber', $error_text);
                }
            }
            else {
                //echo '<pre>'; print_r($model->errors); echo '</pre>';exit;
            }
        }

        $this->render('signup', array('model'=>$model, 'referrer_data' => $referrer_data, 'user_profile2' => $user_data));
    }
}

User model is 用户模型为

    <?php

if ( ! defined('YII_PATH')) exit('No direct script access allowed');

class Users extends CActiveRecord
{

    //variable to confirm passwords
    public $repeat_password;
    public $agree_terms;
    public $agree_referring_affiliate;
    public $agree_subscription;
    public $verifyCode;
    public $referrer;
    public $subid;
    public $token;
    public $cardNumber;
    public $cardCode;
    public $exp_year;
    public $exp_month;
    public $heard_about_us;
    public $agree_refund_policy;
    public $agree_subscription_cancel;


    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'users';
    }

    public function beforeSave(){

        if(parent::beforeSave()){

            // for example
            if(!empty($this->password))
                $this->password = crypt($this->password, '$1$rasmusle$'); // if you save dates as INT

            //echo 'password: '.$this->password;exit;
            return true;
        }
        else
            return false;
    }



    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs. 
        return array(
            array('first_name, last_name, email, phone_no, country, heard_about_us, state, city, zipcode, gender, username, password, registration_date, optin, role, cardNumber, cardCode, exp_year, exp_month', 'required', 'on' => 'signup'),
            array('first_name, last_name, email, phone_no, country,  state, city, zipcode ', 'required','on'=>'edit'),
            array('token', 'validateToken', 'on' => 'signup'),
            array('is_fb, optin, referrer', 'numerical', 'integerOnly'=>true),
            array('first_name, last_name, email, city, country', 'length', 'max'=>45),
            array('username', 'length', 'max'=>20),
            array('username', 'match', 'pattern'=>'/^([a-zA-Z0-9_])+$/', 'message' => 'Username should be alphanumeric and can contain "_" only'),
            array('email', 'email'),
            array('email, username', 'unique', 'on' => 'signup'),   
            array('password, address', 'length', 'max'=>128),
            array('repeat_password', 'compare', 'compareAttribute'=>'password', 'message'=>'Passwords don\'t match'),           
            array('zipcode', 'length', 'max'=>7),
            //array('image', 'length', 'max'=>255),
            //array('image', 'file', 'types'=>'jpg, gif, png'),
            array('status', 'length', 'max'=>8),
            array('cardNumber', 'numerical', 'integerOnly'=>true),
            array('cardNumber', 'length', 'min'=>13),
            array('cardNumber', 'length', 'max'=>17),
            array('cardNumber', 'match', 'pattern'=>'/^([0-9])+$/', 'message' => 'Credit Card Number should be numeric'),

            array('cardCode', 'numerical', 'integerOnly'=>true),
            array('cardCode', 'length', 'min'=>3),
            array('cardCode', 'length', 'max'=>4),
            array('cardCode', 'match', 'pattern'=>'/^([0-9])+$/', 'message' => 'Security Code (CVV) should be numeric'),

            //array('exp_month', 'validateExpMonth', 'on' => 'signup'),

            array('fb_id', 'length', 'max'=>250),
            array('subid', 'unique'),
            array('role', 'length', 'max'=>11),
            array('last_login', 'safe'),

            //array('exp_month', 'ext.validators.CardDateValidator', 'compareValue' => 'exp_year', 'message' => 'failure message'),

            array('agree_refund_policy', 'required', 'message' => 'Please accept Karmora refund policy', 'on' => 'signup'),
            array('agree_subscription', 'required', 'message' => 'Please accept Karmora subscription terms', 'on' => 'signup'),
            array('agree_subscription_cancel', 'required', 'message' => 'Please accept Karmora subscription cancel terms', 'on' => 'signup'),
            //array('agree_referring_affiliate', 'required', 'message' => 'Please accept Karmora referring affiliate terms', 'on' => 'signup'), 

            // Old terms and conditions are changed in new signup page design.
            // array('agree_referring_affiliate', 'required', 'message' => 'Please accept Karmora referring affiliate terms', 'on' => 'signup'),
            // array('agree_terms', 'required', 'message' => 'Please accept Karmora terms and conditions', 'on' => 'signup'),
            // array('agree_subscription', 'required', 'message' => 'Please accept Karmora subscription terms', 'on' => 'signup'),

            // verifyCode needs to be entered correctly
            //array('verifyCode','captcha','allowEmpty'=>!CCaptcha::checkRequirements(), 'on' => 'signup'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, first_name, last_name, username, gender, heard_about_us, email, password, phone_no, registration_date, address, state, city, zipcode, country, image, status, last_login, is_fb, fb_id, optin, role', 'safe', 'on'=>'search'),

        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'favouriteProducts' => array(self::HAS_MANY, 'FavouriteProducts', 'user_id'),
            'favouriteProducts1' => array(self::HAS_MANY, 'FavouriteProducts', 'user_id'),
            'favourites' => array(self::HAS_MANY, 'Favourites', 'user_id'),
            'reminders' => array(self::HAS_MANY, 'Reminder', 'user_id'),
            'traningMaterialPurchases' => array(self::HAS_MANY, 'TraningMaterialPurchase', 'user_id'),
            'userPayments' => array(self::HAS_MANY, 'UserPayments', 'user_id'),
            'usersCommissions' => array(self::HAS_MANY, 'UsersCommission', 'user_referer'),
            'usersCommissions1' => array(self::HAS_MANY, 'UsersCommission', 'user_referral'),
            'usersReferences' => array(self::HAS_MANY, 'UsersReferences', 'user_id'),
            'usersReferences1' => array(self::HAS_MANY, 'UsersReferences', 'referer_id'),
            'usersTransactionsLogs' => array(self::HAS_MANY, 'UsersTransactionsLog', 'user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'username' => 'Username',
            'gender' => 'Gender',
            'email' => 'Email',
            'password' => 'Password',
            'phone_no' => 'Phone No',
            'registration_date' => 'Registration Date',
            'address' => 'Address',
            'state' => 'State',
            'city' => 'City',
            'zipcode' => 'Zipcode',
            'country' => 'Country',
            'image' => 'Image',
            'status' => 'Status',
            'last_login' => 'Last Login',
            'is_fb' => 'Is Fb',
            'fb_id' => 'Fb',
            'optin' => 'Optin',
            'role' => 'Role',
            'heard_about_us'    =>  'Where You Heard About Us',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('first_name',$this->first_name,true);
        $criteria->compare('last_name',$this->last_name,true);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('gender',$this->gender,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('phone_no',$this->phone_no,true);
        $criteria->compare('registration_date',$this->registration_date,true);
        $criteria->compare('address',$this->address,true);
        $criteria->compare('state',$this->state,true);
        $criteria->compare('city',$this->city,true);
        $criteria->compare('zipcode',$this->zipcode,true);
        $criteria->compare('country',$this->country,true);
        $criteria->compare('image',$this->image,true);
        $criteria->compare('status',$this->status,true);
        $criteria->compare('last_login',$this->last_login,true);
        $criteria->compare('is_fb',$this->is_fb);
        $criteria->compare('fb_id',$this->fb_id,true);
        $criteria->compare('optin',$this->optin);
        $criteria->compare('role',$this->role,true);
        $criteria->compare('heard_about_us',$this->heard_about_us,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }


    /*
    public function CardDateValidator($attribute,$params){
        $cur_year = date('Y');

        if($this->compareValue == $cur_year){
                $cut_month = date('m');
        }

        if($cut_month){
            $js = '
                    if($.trim(value)<"' . $cut_month . '") {
                            messages.push("' . $this->message . '");
                    }
                ';
            return $js;
        }
    }*/

    public function validateToken($attribute,$params){

        $token = $this->token;
        if(!empty($token)){

            $command = yii::app()->db->createCommand();
            $admin_data = $command->select('*')
            ->from('fundraising_tokens')
            //->where('role:user_role', array(':user_role' => $user_role))
            ->where("token='". $token."' AND used_by <= 1" )
            ->queryRow();

            if(!$admin_data)
                $this->addError($attribute, 'Invalid token number');
            else
                return true;


        }   

    }

    public function getUsersByRole($user_role){
        $command = yii::app()->db->createCommand();
        $admin_data = $command->select('*')
        ->from($this->tableName())
        //->where('role:user_role', array(':user_role' => $user_role))
        ->where("role='". $user_role."'")
        ->queryRow();

        if($admin_data)
            return $admin_data;
        else
            return false;       
    }

    public function getUsersByUserName($user_name){
        $command = yii::app()->db->createCommand();
        $admin_data = $command->select('*')
        ->from($this->tableName())
        //->where('role:user_role', array(':user_role' => $user_role))
        ->where("username='". $user_name."'")
        ->queryRow();

        if($admin_data)
            return $admin_data;
        else
            return false;
    }

    public function getUserIdByUsername($username){

        $detail = yii::app()->db->createCommand()
        ->select('u.id')
        ->from('users u')
        ->where('u.username=:username', array(':username'=>$username))
        ->queryAll();

        if($detail)
            return $detail[0];
        else
            return FALSE;
    }

}

Make that attribute safe in model -> rules : 使该属性在模型中安全->规则:

    public function rules() {
    return array(
    // other rules
    array('attribute_name_that_is_not_inserting', 'safe'),
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM